[英]Getting XML number of nodes in a xml file with the same node name using DOM
[英]trying to update the same XML file with a new XML nodes using the tag name
我正在創建一個簡單的 java 函數來更新/重寫 xml 文件的值。 我能夠從系統資源中選擇 XML 文件,更新文件並重寫后,節點的值永遠不會改變。
這是我的片段:
String filePath = ABS_PATH + File.separator + "fields.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
//update Element value
updateElementValue(doc);
//write the updated document to file or console
doc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(ABS_PATH
+ File.separator + "fields.xml")); // updating/re-writing the same file
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
e1.printStackTrace();
}
//method to show the update element value
private static void updateElementValue(Document doc) {
NodeList employees = doc.getElementsByTagName("NO");
Element emp = null;
//loop for each
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element)employees.item(i);
Node name = emp.getElementsByTagName("String").item(0).getFirstChild();
name.setNodeValue(name.getNodeValue().toUpperCase());
}
}
xml文件示例
<Document xmlns="http://hello.com/schema/public/services/platform" Id="1">
<Fields>
<Field FieldName="NO">
<String>Demo</String>
</Field>
<Field FieldName="TYPE">
<String>Zada</String>
</Field>
</Fields>
誰有足夠的動力提供幫助
您有以下聲明:
NodeList employees = doc.getElementsByTagName("NO");
它將返回一個空列表,因為您的 XML 沒有任何帶有“NO”作為標簽的節點。
<Field FieldName="NO">
循環中遍歷列表的語句將永遠不會執行。 您的節點將不會更新。
帶有標簽Field
元素具有屬性FieldName
。 其中之一的屬性值為“NO”。 所以你需要找到它。
查看如何獲取具有特定屬性值的特定 XML 元素? 給你足夠的指導。
你也可以用循環來做。
NodeList employees = doc.getElementsByTagName("Field");
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element)employees.item(i);
if ("NO".equals(emp.item(i).getAttribute("FieldName"))) {
// do your stuff
}
}
以上未測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.