1

Hello this is my xml document :

<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>

I want to update the rating of "jojo" restaurant in jbeil from 4.3/5 to 4.5/5 using xpath and netbeans please help ,

this code give the rating ,

  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());

and i want only to update the rating of restaurant in jbeil where name is "jojo" , please help

har07
  • 88,338
  • 12
  • 84
  • 137

1 Answers1

1

This is one possible XPath to find such restaurant named jojo in the city of jbeil and then return the corresponding rating element :

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

Notice that XML & XPath are case-sensitive, so I used all lower-case characters in the above XPath to match the XML posted in this question.

I don't know much about Java, but quick searching over the internet* suggest something like this :

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?

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137
  • I was working on a similar example. My implementation is returning a `DeferredTextImpl` instance that actually can't be case to an Element type. It can, however, be case to a `Node`, which is actually the interface containing the `setTextContent` method. And in case anyone is wondering which `Node` it is, it's a `org.w3c.dom.Node`. – jwj Jan 09 '18 at 07:24