我只想更改jojo餐厅的等级,我尝试了此代码,但是没有用,请帮助。以下是我的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>
码:
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/Restaurants/Restaurant[name='Feniqia']/rating";
Element e = (Element)xPath.evaluate(expression, doc, XPathConstants.NODE);
if (e != null){
e.setTextContent("5/5");
}
} catch (ParserConfigurationException | SAXException | IOException e) {
}
最佳答案
如果您只需要写结果(还有其他方法):
导入java.io.File;
import org.w3c.dom.Document;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
try
{
Transformer trans = TransformerFactory.newInstance().newTransformer();
Result out = new StreamResult(new File("result.xml"));
Source in = new DOMSource(doc);
trans.transform(in, out);
}
catch (Exception exe)
{
System.err.println(exe.getMessage());
}