Results 1 to 7 of 7
  1. #1
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default Get selected Node Value of a child element

    Hi

    I am using DOM to parse an xml file.Below is my xml file
    Java Code:
    <?xml version="1.0"?>
    <root>
    <parent att1="val1">
    <child1>childvalue</child1>
    <child2 att2="val2">
    <child3>10093</child3>
    <sibling att3="val3"/>
    </child2>
    </parent>
    </root>
    The code to extract text node value
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.parsers.*;
    import org.omg.CORBA.Any;
    import org.w3c.dom.*;
    public class Parsing {
    private static final String FILE_NAME_STRING = "test.xml";
    
    public static void main(String args[]) {
      List childlist = new ArrayList();
      try {
        
        DocumentBuilder builder;  
        DocumentBuilderFactory factory = DocumentBuilderFactory
            .newInstance();  
        builder = factory.newDocumentBuilder();
        Document document = builder.parse(FILE_NAME_STRING);    
        Element node = document.getDocumentElement();
        recurseThroughDoc(node);
    
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    
    private static void recurseThroughDoc(Node node) {
    		
      int type = node.getNodeType();
       if (type == Node.TEXT_NODE && !(node.getNodeValue()==null)&& !(node.getNodeValue()=="")) {
        //System.out.println("Type: Text Node");
        System.out.println("Value: " + node.getNodeValue() + "");
      } 
      NodeList nodeList = node.getChildNodes();  
      if (nodeList.getLength() > 0) {
        for (int i = 0; i < nodeList.getLength(); i++) {
          recurseThroughDoc(nodeList.item(i));
        }
      }}
    }
    The output which i get is
    Java Code:
    Value: 
    
    Value: 
    
    Value: childvalue
    Value: 
    
    Value: 
    
    Value: 10093
    Value: 
    
    Value: 
    
    Value: 
    
    Value:
    But what i actually want is only the value:10093,the child3 element's node value.Since its of type text node,when i try to get the nodename i get #text
    So how do i get only the nodevalue of child3 alone??

    Any suggesstion please...
    Thanks

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Also, this is a no-no:
    Java Code:
    if (type == Node.TEXT_NODE && !(node.getNodeValue()==null)&& !(node.getNodeValue()=="")) {
    as you should almost never compare Strings with ==.

    This may work better:
    Java Code:
    if (type == Node.TEXT_NODE && !(node.getNodeValue()==null)&& !(node.getNodeValue().trim().isEmpty())) {

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Here's an example using XPath, but I warn you that I'm still a neophyte with this and there may be errors. If anyone sees any, please correct:

    Java Code:
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathExpressionException;
    import javax.xml.xpath.XPathFactory;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    
    public class XPathReader1 {
    
       //  **** you'll have to change the path string to match your needs
       private static final String XML_PATH_STRING = "src/yr2009/m09/b/test.xml";
       private static final String XPATH_EXPRESSION = "//child3/text()";
    
       public static List<String> getTraceNumbers(String path, String expression)
                throws ParserConfigurationException, SAXException, IOException,
                XPathExpressionException {
          DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
          domFactory.setNamespaceAware(true);
          DocumentBuilder builder = domFactory.newDocumentBuilder();
          Document doc = builder.parse(new File(path));
    
          XPathFactory xFactory = XPathFactory.newInstance();
          XPath xpath = xFactory.newXPath();
          XPathExpression expr = xpath.compile(expression);
    
          Object result = expr.evaluate(doc, XPathConstants.NODESET);
          NodeList nodes = (NodeList) result;
          List<String> vOne = new ArrayList<String>();
          for (int i = 0; i < nodes.getLength(); i++) {
             String nodeText = nodes.item(i).getNodeValue().trim();
             vOne.add(nodeText);
          }
    
          return vOne;
       }
    
       public static void main(String[] args) throws XPathExpressionException,
                ParserConfigurationException, SAXException, IOException {
          System.out.println(getTraceNumbers(XML_PATH_STRING, XPATH_EXPRESSION));
       }
    
    }

  5. #5
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default

    Thanks,I will go through the code and learn about XPath,its sad that i could not do with dom,anyway thanks....

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Ms.Ranjan View Post
    Thanks,I will go through the code and learn about XPath,its sad that i could not do with dom,anyway thanks....
    It can be done with DOM, never said it couldn't. Did you read my comment about your using == to compare Strings?

  7. #7
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default

    yes,its the sample code that i use for testing purpose and clarifying issues,my original one does have the change,i will the change in this also..

    Thanks.
    PS: I'd appreciate if you could suggest me on how to deal the issue with dom too..

Similar Threads

  1. How to add different menuitems to child node
    By sudhakar.cheru in forum AWT / Swing
    Replies: 2
    Last Post: 09-16-2009, 07:32 AM
  2. How to get value of specific child node
    By sito42 in forum New To Java
    Replies: 1
    Last Post: 07-13-2009, 01:00 PM
  3. Cannot add or update a child row....
    By Pierced1 in forum JDBC
    Replies: 2
    Last Post: 06-29-2009, 03:32 AM
  4. Replies: 3
    Last Post: 11-21-2008, 08:43 AM
  5. Replies: 1
    Last Post: 10-17-2008, 11:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •