我只想更改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) {
  }发布于 2015-11-30 06:16:15
首先,您的XPath没有与发布的XML对齐(没有<restaurants>或Feniqia名称),而且所有内容都应该是小写的。您可能从大型xml文档中提取了一部分。为了进行演示,我使用了jojo餐厅。
其次,XPath本身不会更新XML,您需要创建一个新文档。只需在结尾处添加一个转换:
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
import java.io.File;
import java.io.IOException;
import org.xml.sax.*;
import org.w3c.dom.*;
public class RatingUpdate {    
    public static void main(String [] args) {
          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[name='jojo']/rating"; 
               Element e = (Element)xPath.evaluate(expression, doc, XPathConstants.NODE);
               if (e != null){
                  e.setTextContent("5/5");
               }
               Transformer xformer = TransformerFactory.newInstance().newTransformer();
               xformer.transform(new DOMSource(doc), new StreamResult(new File("src/xpath/josephXml_update.xml")));
             } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException |
                      TransformerException e) {
          }
    }
}https://stackoverflow.com/questions/33986034
复制相似问题