开发者

How to traverse into CDATA in XML using Java

开发者 https://www.devze.com 2023-03-02 14:30 出处:网络
I have an XML file like this <params> <param index=\"0\"> <value> <![CDATA[value1]]>

I have an XML file like this

 <params>
            <param index="0">
              <value>
                <![CDATA[value1]]>
              </value>
            </param>
            <param index="1">
              <value>
                <![CDATA[value2]]>
              </value>
            </param>
            <param index="2">
              <value>
                <![CDATA[value3]]>
              </value>
            </param>
            <param index="3">
              <value>
                <![CDATA[value4]]>
              </value>
            </param>
          <开发者_如何学C;/params>

I want to get Value1 only. Can anyone please help in finding the solution for this


If you just want value1, you could use something like XPath to grab that value:-

try {
    InputStream is = getClass().getClassLoader().getResourceAsStream("data.xml");
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
    XPath xPath = XPathFactory.newInstance().newXPath();
    String value = xPath.evaluate("//param[@index='0']/value/text()", doc).trim();
    System.out.println("Value: " + value);
}
catch (Exception e) {
    e.printStackTrace();
}

... and yes, consider up-voting and accepting the answers from your past questions. You will find that folks are unwilling to help you if you don't take the simple effort to show your appreciations. :)


import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("data.xml");
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(file);

    NodeList nodes = doc.getElementsByTagName("topic");
    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);
      NodeList title = element.getElementsByTagName("title");
      Element line = (Element) title.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }
  }
  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterData) child;
      return cd.getData();
    }
    return "";
  }
}

http://www.java2s.com/Code/Java/XML/GetcharacterdataCDATAfromxmldocument.htm


Please see my solution. It's more general. You solutions won't work for some possible cases.

 private static String getCharacterDataFromElement(Element e) {
        String queryText = null;
        NodeList nl = e.getChildNodes();
        for(int i=0; i<nl.getLength();i++){
            if(nl.item(i).getNodeType() == Node.CDATA_SECTION_NODE){
                queryText = nl.item(i).getNodeValue().trim();
                break;
            }
        }
        return queryText;
    }

Try to use your solution with such case:

<query name="persistRating">
<![CDATA[
    INSERT INTO scoring_cache (resourcetypeid, resourceid, contentid, sumhitcount) values (?, ?, ?, ?)
]]>

your

Node child = e.getFirstChild();

will return type text, not type cdata. And you won't get your text from CDATA.

0

精彩评论

暂无评论...
验证码 换一张
取 消