将XML String中的所有CDATA读入Java ArrayList?

时间:2011-10-14 17:33:01

标签: java xml xml-parsing

我想读取与子节点关联的所有CDATA并将它们存储到java ArrayList中!如果您能建议一种简单快捷的方式,我会非常感激它!

谢谢!

希望对txnid进行一些特定的例行测试,并读取不同数组元素中的所有相关CDATA查询。

 <?xml version="1.0" encoding="utf-8" standalone="yes" ?> 
 <ZQueries txid="Group 1" version="1.0.0.0">
 <ZQuery name="Some Name 1" savename="SomeFileName1.xml">
  <![CDATA[ 
      SELECT ...........

  ]]> 
 </ZQuery>
 <ZQuery name="Some Name 2"   savename="SomeFileName.xml">
 <![CDATA[ 
    SELECT .............


  ]]> 
</ZQuery>
<ZQuery name="some name 3" savename="someFileName.xml">
<![CDATA[ 
    SELECT ..............

 ]]> 
 </ZQuery>
 </ZQueries>
 <ZQueries txid="Group 2" version="1.0.0.0">
 <ZQuery name="Some Name 1" savename="SomeFileName1.xml">
  <![CDATA[ 
      SELECT ...........

  ]]> 
 </ZQuery>
 <ZQuery name="Some Name 2"   savename="SomeFileName.xml">
 <![CDATA[ 
    SELECT .............


  ]]> 

 </ZQueries>

这是正确的方法!以下代码创造了例外情况!你怎么认为我可以得到这个!

 SAXBuilder builder = new SAXBuilder();
 Document doc = builder.build(in);  //build a JDOM doc from an input stream
 ArrayList<String> queries = new ArrayList<String>();
 Element root = doc.getRootElement();

 Iterator elemIter = root.getDescendants();

 while (elemIter.hasNext()) {
     Element tempElem = (Element) elemIter.next();
     if (root.getChild("ZQueries").getAttributeValue("txnid").equals(tempTxnid)) {
         String CDATA = tempElem.getChildText("ZQueries");
         queries.add(CDATA);
     } 
 }



Exception in thread "AWT-EventQueue-0" java.security.PrivilegedActionException:
java.security.PrivilegedActionException: org.jdom.input.JDOMParseException: Error on 
line 1: Premature end of file.

2 个答案:

答案 0 :(得分:0)

使用SAX Parser:

try {
    // Create a builder factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Configure it to coalesce CDATA nodes
    factory.setCoalescing(true);

    // Create the builder and parse the file
    // Perform your Parsing here 

    // doc will not contain any CDATA nodes
} catch (SAXException e) {
    // A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}

答案 1 :(得分:0)

使用JDOM。在解析文档之前,请创建一个Array列表,可能是string类型。迭代元素,当你点击ZQuery元素时,使用element.getChildText(“ZQuery”),它将返回没有CDATA标记的所有CDATA信息。

FileInputStream fis = new FileInputStream(file); //where file holds the data to parse. 

Can also use StringBuilder
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(fis); //build a JDOM doc from file
ArrayList<String> arl = new ArrayList<String>();
Element root = doc.getRootElement();
Iterator elemIter = root.getDescendants(); //you can put filters on this to only get specific types of elements ie: root.getDescendants("ZQuery"); will give you an iterator over just ZQuery elements. 

while (elemIter.hasNext()) {
    Element foo = (Element) elemIter.next();
    String CDATA = foo.getChildText("ZQuery")
    arl.add(CDATA);
}

其他资源: