如何使用XPath和Java更新XML [英] How to update XML using XPath and Java
问题描述
我有一个XML文档,以及该doc的XPath表达式。我必须在运行时使用XPath来更新文档。
I have an XML document, and an XPath expression for that doc. I have to update the doc by using XPath at runtime.
如何使用Java执行此操作?
How can I do this using Java?
以下是我的xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<PersonList>
<Person>
<Name>Sonu Kapoor</Name>
<Age>24</Age>
<Gender>M</Gender>
<PostalCode>54879</PostalCode>
</Person>
<Person>
<Name>Jasmin</Name>
<Age>28</Age>
<Gender>F</Gender>
<PostalCode>78745</PostalCode>
</Person>
<Person>
<Name>Josef</Name>
<Age>232</Age>
<Gender>F</Gender>
<PostalCode>53454</PostalCode>
</Person>
</PersonList>
我必须在 // PersonList /下更改名称和年龄的值Person [2] / Name
。
推荐答案
使用 setNodeValue
。首先,获取一个NodeList,例如:
Use setNodeValue
. First, get a NodeList, for example:
myNodeList = (NodeList) xpath.compile("//MyXPath/text()")
.evaluate(myXmlDoc, XPathConstants.NODESET);
然后设置例如第一个节点:
Then set the value of e.g. the first node:
myNodeList.item(0).setNodeValue("Hi mom!");
更多例子,例如此处。
正如此处的另外两个答案中所述,以及上一个问题:从技术上讲,XPath不是更新XML文档的方法,而只是在XML文档中定位节点。但我认为以上就是你想要的。
As mentioned in two other answers here, as well as in your previous question: technically, XPath is not a way to "update" an XML document, but only to locate nodes within an XML document. But I presume the above is what you want.
编辑:回复您的评论...您是否在询问如何将您的DOM写入XML文件你完成DOM编辑后?如果是这样,以下是两个如何操作的示例:
EDIT: Responding to your comment... Are you asking how to write your DOM to an XML file after you've finished editing the DOM? If so, here are two examples of how to do it:
http://www.java2s.com/Code/Java/XML/WriteDOMout.htm
http://download.oracle.com/javaee/1.4/tutorial/doc/ JAXPXSLT4.html
这篇关于如何使用XPath和Java更新XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!