您好,这是我的xml文档:
<city>
<beirut>
<restaurant>
<name>sada</name>
</restaurant>
</beirut>
<jbeil>
<restaurant>
<name>toto</name>
<rating>4.3/5</rating>
</restaurant>
<restaurant>
<name>jojo</name>
<rating>4.3/5</rating>
</restaurant>
</jbeil>
<sour>
<restaurant>
<name>sada</name>
</restaurant>
</sour>
</city>
我想更新&#34; jojo&#34;的评分jbeil的餐厅从4.3 / 5到4.5 / 5使用xpath和netbeans请帮忙,
此代码给出评级,
try {
File inputFile = new File("src/xpath/josephXml.xml");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/City/Jbeil/Restaurant";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode = nodeList.item(i);
System.out.println("\nCurrent Element :"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("rating : "
+ eElement
.getElementsByTagName("rating")
.item(0)
.getTextContent());
我只想更新jbeil餐厅的评级,其名称是&#34; jojo&#34; ,请帮忙
答案 0 :(得分:1)
这是一个可能的XPath,可以在jojo
城找到名为jbeil
的餐馆,然后返回相应的rating
元素:
/city/jbeil/restaurant[name='jojo']/rating
请注意XML&amp; XPath区分大小写,因此我使用上述XPath中的所有小写字符来匹配此问题中发布的XML。
我对Java知之甚少,但通过互联网快速搜索*建议如下:
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/city/jbeil/restaurant[name='jojo']/rating";
Element e = (Element)xpath.evaluate(expression, doc, XPathConstant.NODE);
if (e != null)
e.setTextContent("4.5/5");