gpt4 book ai didi

java - 使用 xpath 更新 xml 文档

转载 作者:行者123 更新时间:2023-11-30 07:45:42 25 4
gpt4 key购买 nike

您好,这是我的 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>

我想使用 xpath 和 netbeans 将 jbeil 的“jojo”餐厅的评级从 4.3/5 更新到 4.5/5,请帮忙,

此代码给出评级,

  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 名称为“jojo”的餐厅的评级,请帮忙

最佳答案

这是一种可能的 XPath,用于在 jbeil 市查找名为 jojo 的餐厅,然后返回相应的 rating 元素:

/city/jbeil/restaurant[name='jojo']/rating

请注意,XML 和 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");

*) how to modify xml tag specific value in java?

关于java - 使用 xpath 更新 xml 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33982272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com