英文:
Java XML How to - Use xpath to find and add/replace more children to a Nodelist in an XML file
问题
public void Write2XMLfile(){
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
try {
// ...
// Retrieve the node corresponding to the 'planlagtAntallPerUndergruppe' array
Node planlagtAntallPerUndergruppe = (Node) xpath.evaluate("/map/array[@key='planlagtAntallPerUndergruppe']", doc, XPathConstants.NODE);
if (null != planlagtAntallPerUndergruppe) {
// Loop through the array elements
for (int j = 0; j < planlagtAntallPerUndergruppe_antall_value.length; j++) {
// Create a new 'map' element
Element mapElement = doc.createElement("map");
// Create 'number' element for 'antall' and set its value
Element antallElement = doc.createElement("number");
antallElement.setAttribute("key", "antall");
antallElement.appendChild(doc.createTextNode(planlagtAntallPerUndergruppe_antall_value[j]));
mapElement.appendChild(antallElement);
// Create 'string' element for 'kode' and set its value
Element kodeElement = doc.createElement("string");
kodeElement.setAttribute("key", "kode");
kodeElement.appendChild(doc.createTextNode(planlagtAntallPerUndergruppe_kode_value[j]));
mapElement.appendChild(kodeElement);
// Append the 'map' element to 'planlagtAntallPerUndergruppe'
planlagtAntallPerUndergruppe.appendChild(mapElement);
}
}
// ...
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done Updating The Api_XML_Format.xml");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
} catch (XPathExpressionException xee) {
xee.printStackTrace();
}
}
英文:
I have an xml file (ToThis.xml) that i am updating with array variables. Am using Xpath to update to this xml file but i can only update the first array element. see below .
xml file (ToThis.xml) what i get
<?xml version="1.0" encoding="UTF-8"?><map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="ankomstDato">2020-08-20</string>
<array key="planlagtAntallPerUndergruppe">
<map>
<number key="antall">67</number>
<string key="kode">SLAKTEGRIS</string>
</map>
</array>
</map>
xml file that i would like to get should be like this below
<?xml version="1.0" encoding="UTF-8"?><map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="ankomstDato">2020-08-20</string>
<array key="planlagtAntallPerUndergruppe">
<map>
<number key="antall">67</number>
<string key="kode">SLAKTEGRIS</string>
</map>
<map>
<number key="antall">4</number>
<string key="kode">UNGSAU</string>
</map>
</array>
</map>
Below is portion of the code where it get me the first result. NOTE( The two array variable in real scenario are not hard coded they are assigned dynamically)
public void Write2XMLfile(){
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
try {
//
String filepath = "E:/utils/Tothis.xml";
//
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
planlagtAntallPerUndergruppe_antall_value[0] = "67";
planlagtAntallPerUndergruppe_kode_value[0] = "SLAKTEGRIS";
planlagtAntallPerUndergruppe_antall_value[1] = "4";
planlagtAntallPerUndergruppe_kode_value[1] = "UNGSAU";
//2. planlagtAntallPerUndergruppe **************************
System.out.println("\n This is second" );
Node planlagtAntallPerUndergruppe = (Node) xpath.evaluate("/map/array[@key='planlagtAntallPerUndergruppe']/*", doc, XPathConstants.NODE);
if(null != planlagtAntallPerUndergruppe) {
NodeList nodeList = planlagtAntallPerUndergruppe.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++) {
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE){
NodeList arrayElements_18 = (NodeList) xpath.evaluate("/map/array[@key='planlagtAntallPerUndergruppe']/*", doc, XPathConstants.NODESET);
//System.out.println("\n number of elements" + arrayElements_18.getLength());
for (int j = 0; j < arrayElements_18.getLength(); j++) {
//. antall
Node antall = (Node) xpath.evaluate("(/map/array/map/number[@key='antall'])[1]", doc, XPathConstants.NODE);
antall.setTextContent(planlagtAntallPerUndergruppe_antall_value[j]);
// end antall
//. kode
Node kode = (Node) xpath.evaluate("(/map/array/map/string[@key='kode'])[1]", doc, XPathConstants.NODE);
kode.setTextContent(planlagtAntallPerUndergruppe_kode_value[j]);
//System.out.println("\n\n antall: " + planlagtAntallPerUndergruppe_antall_value[j]);
// end kode
}
}
}
}
// end array planlagtAntallPerUndergruppe
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done Updating The Api_XML_Format.xml");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
} catch (XPathExpressionException xee) {
xee.printStackTrace();
}
}
答案1
得分: 2
XPath被有意地用于跟踪/读取XML,但不能用于修改XML。
因此,我将代码从使用XPath更改为使用DOM解析器。
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// 创建根元素 "map"
Element rootElement = doc.createElement("map");
doc.appendChild(rootElement);
// 根元素下的子元素
// 1. 创建 "string" 元素 "ankomstDato"
Element ankomstDato = doc.createElement("string");
Attr attrType_ankomstDato = doc.createAttribute("key");
attrType_ankomstDato.setValue("ankomstDato");
ankomstDato.setAttributeNode(attrType_ankomstDato);
ankomstDato.appendChild(doc.createTextNode(ankomstDato_value));
rootElement.appendChild(ankomstDato);
// 创建 "array" 元素 "planlagtAntallPerUndergruppe"
if (planlagtAntallPerUndergruppe_Count != 0) {
Element planlagtAntallPerUndergruppe = doc.createElement("array");
rootElement.appendChild(planlagtAntallPerUndergruppe);
Attr attr = doc.createAttribute("key");
attr.setValue("planlagtAntallPerUndergruppe");
planlagtAntallPerUndergruppe.setAttributeNode(attr);
for (int i = 0; i < planlagtAntallPerUndergruppe_Count; i++) {
Element map1 = doc.createElement("map");
planlagtAntallPerUndergruppe.appendChild(map1);
// 添加 "number" 元素 "antall"
Element antall = doc.createElement("number");
Attr attrType = doc.createAttribute("key");
attrType.setValue("antall");
antall.setAttributeNode(attrType);
antall.appendChild(doc.createTextNode(planlagtAntallPerUndergruppe_antall_value[i]));
map1.appendChild(antall);
// 添加 "string" 元素 "kode"
Element kode = doc.createElement("string");
Attr attrType1 = doc.createAttribute("key");
attrType1.setValue("kode");
kode.setAttributeNode(attrType1);
kode.appendChild(doc.createTextNode(planlagtAntallPerUndergruppe_kode_value[i]));
map1.appendChild(kode);
}
}
// 结束 "planlagtAntallPerUndergruppe"
// 将内容写入XML文件
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("E:/utils/students-new.xml"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// 格式化XML输出
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(source, result);
}
catch (Exception ex) {
ex.printStackTrace();
}
英文:
Xpath is purposely used to trace/read through an xml but cannot be used to modify an xml.
So, I changed my code from using XPath to using DOM Parser.
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Map root element
Element rootElement = doc.createElement("map");
doc.appendChild(rootElement);
//ROOT map
//1. ankomstDato
Element ankomstDato = doc.createElement("string");
Attr attrType_ankomstDato = doc.createAttribute("key");
attrType_ankomstDato.setValue("ankomstDato");
ankomstDato.setAttributeNode(attrType_ankomstDato);
ankomstDato.appendChild(doc.createTextNode(ankomstDato_value));
rootElement.appendChild(ankomstDato);
//. planlagtAntallPerUndergruppe
// planlagtAntallPerUndergruppe element
if (planlagtAntallPerUndergruppe_Count !=0){
Element planlagtAntallPerUndergruppe = doc.createElement("array");
rootElement.appendChild(planlagtAntallPerUndergruppe);
Attr attr = doc.createAttribute("key");
attr.setValue("planlagtAntallPerUndergruppe");
planlagtAntallPerUndergruppe.setAttributeNode(attr);
for (int i = 0; i < planlagtAntallPerUndergruppe_Count; i ++){
//to add "map" element
Element map1 = doc.createElement("map");
planlagtAntallPerUndergruppe.appendChild(map1);
// antall element
Element antall = doc.createElement("number");
Attr attrType = doc.createAttribute("key");
attrType.setValue("antall");
antall.setAttributeNode(attrType);
antall.appendChild(doc.createTextNode(planlagtAntallPerUndergruppe_antall_value[i]));
map1.appendChild(antall);
//kode element
Element kode = doc.createElement("string");
Attr attrType1 = doc.createAttribute("key");
attrType1.setValue("kode");
kode.setAttributeNode(attrType1);
kode.appendChild(doc.createTextNode(planlagtAntallPerUndergruppe_kode_value[i]));
map1.appendChild(kode);
}
}
//end planlagtAntallPerUndergruppe
// Write the content into XML file
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("E:/utils/students-new.xml"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// Beautify the format of the resulted XML
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(source, result);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
答案2
得分: 1
将收集到的数组作为参数传递给 Write2XMLfile
方法
public void Write2XMLfile(String[] planlagtAntallPerUndergruppe_antall_value, String[] planlagtAntallPerUndergruppe_kode_value) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
Element rootElement = doc.createElement("map");
doc.appendChild(rootElement);
Element mainString = doc.createElement("string");
mainString.setAttribute("key", "ankomstDato");
rootElement.appendChild(mainString).setTextContent("2020-08-20");
Element array = doc.createElement("array");
array.setAttribute("key", "planlagtAntallPerUndergruppe");
rootElement.appendChild(array);
if(planlagtAntallPerUndergruppe_antall_value.length > 0){
for (int i = 0; i < planlagtAntallPerUndergruppe_antall_value.length; i++) {
Element map = doc.createElement("map");
array.appendChild(map);
Element number = doc.createElement("number");
number.setAttribute("key", "antall");
map.appendChild(number).setTextContent(planlagtAntallPerUndergruppe_antall_value[i]);
Element string = doc.createElement("string");
string.setAttribute("key", "kode");
map.appendChild(string).setTextContent(planlagtAntallPerUndergruppe_kode_value[i]);
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult output = new StreamResult(new File("output.xml"));
transformer.transform(source, output);
} catch (Exception e) {
e.printStackTrace();
}
}
output.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<map>
<string key="ankomstDato">2020-08-20</string>
<array key="planlagtAntallPerUndergruppe">
<map>
<number key="antall">67</number>
<string key="kode">SLAKTEGRIS</string>
</map>
<map>
<number key="antall">4</number>
<string key="kode">UNGSAU</string>
</map>
</array>
</map>
英文:
pass collected arrays into Write2XMLfile
method as parameters
public void Write2XMLfile(String[] planlagtAntallPerUndergruppe_antall_value, String[] planlagtAntallPerUndergruppe_kode_value) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
Element rootElement = doc.createElement("map");
doc.appendChild(rootElement);
Element mainString = doc.createElement("string");
mainString.setAttribute("key", "ankomstDato");
rootElement.appendChild(mainString).setTextContent("2020-08-20");
Element array = doc.createElement("array");
array.setAttribute("key", "planlagtAntallPerUndergruppe");
rootElement.appendChild(array);
if(planlagtAntallPerUndergruppe_antall_value.length>0){
for (int i = 0; i < planlagtAntallPerUndergruppe_antall_value.length; i++) {
Element map = doc.createElement("map");
array.appendChild(map);
Element number = doc.createElement("number");
number.setAttribute("key", "antall");
map.appendChild(number).setTextContent(planlagtAntallPerUndergruppe_antall_value[i]);
Element string = doc.createElement("string");
string.setAttribute("key", "kode");
map.appendChild(string).setTextContent(planlagtAntallPerUndergruppe_kode_value[i]);
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult output = new StreamResult(new File("output.xml"));
transformer.transform(source, output);
} catch (Exception e) {
e.printStackTrace();
}
}
output.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<map>
<string key="ankomstDato">2020-08-20</string>
<array key="planlagtAntallPerUndergruppe">
<map>
<number key="antall">67</number>
<string key="kode">SLAKTEGRIS</string>
</map>
<map>
<number key="antall">4</number>
<string key="kode">UNGSAU</string>
</map>
</array>
</map>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论