简体   繁体   English

如何使用 Java 遍历 XML 中的 CDATA

[英]How to traverse into CDATA in XML using Java

I have an XML file like this我有一个像这样的 XML 文件

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

I want to get Value1 only.我只想获得 Value1 。 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:-如果您只想要value1 ,您可以使用 XPath 之类的东西来获取该值:-

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.你会发现如果你不努力表达你的感激之情,人们就不愿意帮助你。 :) :)

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.将返回类型文本,而不是类型 cdata。 And you won't get your text from CDATA.而且您不会从 CDATA 获得您的文本。

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 http://www.java2s.com/Code/Java/XML/GetcharacterdataCDATAfromxmldocument.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM