[英]how to retrieve from a specific XML element in java
What line code can I add in my method that will only modify the tagname "location" as LONG AS IT CONTAINS A SPECIFIC information under the node named "address?" 我可以在我的方法中添加什么行代码,以仅将标记名“ location”修改为Long,因为它包含名为“ address”的节点下的特定信息? So if i update "color" or "size" then I can tell the nodeList: "change these values only if it contains 123 Main Street in "address." I've tried all types of "equal etc." note: I created an object that i use object.getAddress as my variable that i want to check against. XML has 50 entries: 因此,如果我更新“颜色”或“大小”,那么我可以告诉nodeList:“仅当它在“地址”中包含123 Main Street时,才更改这些值。我已经尝试了所有类型的“等于等”。注意:我创建了我使用object.getAddress作为我要检查的变量的对象XML有50个条目:
<location>
<address>123 Main Street</address>
<color>red</color>
<size>large</size>
</location>
public void changeValue(Document doc, String oldValue, String NewValue) throws Exception {
Element root = doc.getDocumentElement();
NodeList childNodes = root.getElementsByTagName("location");
for (int i = 0; i < childNodes.getLength(); i++) {
NodeList subChildNodes = childNodes.item(i).getChildNodes();
for (int j = 0; j < subChildNodes.getLength(); j++) {
try {
if (subChildNodes.item(j).getTextContent().equals(oldValue)) {
subChildNodes.item(j).setTextContent(NewValue);
}
} catch (Exception e) {
}
}
}
File file = new File("XMLDatabase.xml");
save(file, doc);
}
I hope this helps! 我希望这有帮助!
for (int i = 0; i < childNodes.getLength(); i++) {
NodeList subChildNodes = childNodes.item(i).getChildNodes();
for (int j = 0; j < subChildNodes.getLength(); j++) {
try {
if (subChildNodes.item(j).getTextContent().equals("123 Main Street")) {
int temp=j;
subChildNodes.item(temp).setTextContent("value you want to set");
subChildNodes.item(temp+2).setTextContent("value you want to set");
subChildNodes.item(temp+4).setTextContent("value you want to set");
}
} catch (Exception e) {
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.