java - 使用 XmlUtils 解析 XML

标签 java xml parsing jdom

我正在使用 XmlUtils 解析并提取列表中 id 属性的值,但它返回空。

我哪里出错了?请推荐

XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<address-book xmlns="qwerty" xmlns:ab2="asdfgh">
<contact time-stamp="2014-02-26T16:35:20.678+02:00" id="12345">
    <ns2:person-details index="9AmmUzHXBPsK:96">
        <ns2:name index="1">
            <ns2:name-entry index="1">
                <ns2:display-name>DISP0dNXoq</ns2:display-name>
                <ns2:given display-order="1">GIVENw17JCb</ns2:given>
                <ns2:family display-order="1">FAMILYcl7h2y</ns2:family>
            </ns2:name-entry>
        </ns2:name>
        <ns2:comm-addr xml:lang="en">
            <ns2:uri-entry addr-uri-type="trn" index="1:1111">
                <ns2:addr-uri>cnaFC@hOog6.com</ns2:addr-uri>
                <ns2:label xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
            </ns2:uri-entry>
            <ns2:tel tel-type="Home" index="2:22222">
                <ns2:tel-nb>
                    <ns2:tel-str>97235852622</ns2:tel-str>
                </ns2:tel-nb>
            </ns2:tel>
            <ns2:tel tel-type="Work" index="3:33333">
                <ns2:tel-nb>
                    <ns2:tel-str>97230557837</ns2:tel-str>
                </ns2:tel-nb>
            </ns2:tel>
            <ns2:tel tel-type="Mobile" index="3:33333">
                <ns2:tel-nb>
                    <ns2:tel-str>972542993697</ns2:tel-str>
                </ns2:tel-nb>
            </ns2:tel>
        </ns2:comm-addr>
    </ns2:person-details>
    <contact-status>
        <contact-source>contact-source-sim-1393425320678</contact-source>
    </contact-status>
</contact>
<contact time-stamp="2014-02-26T16:37:19.370+02:00" id="12346">
<contact time-stamp="2014-02-26T16:38:53.345+02:00" id="12347">
<contact time-stamp="2014-02-26T16:37:30.828+02:00" id="12348">

代码:

Document document = XmlUtils.createDocument(responseString);
List<Element> list = document.getRootElement().getChildren("address-book");
for( Element ele : list){
    System.out.println(ele.getChild("contact").getAttribute("id").getValue());
}

XmlUtils 类-

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xml.sax.InputSource;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.FileWriter;

public class XmlUtils
{
private static final Logger logger = Logger.getLogger(XmlUtils.class);
public static String getFormatedXMLString(String doc)  throws JDOMException, IOException
{
    return (  makeDomToFormatedString( createDocument(doc)  ) ) ;
}

public static String makeDomToFormatedString(Document doc)
{
    return makeDomToFormatedString(doc.getRootElement());
}

public static String makeDomToFormatedString(Element elem)
{
    XMLOutputter output = new XMLOutputter();

    Format format = Format.getPrettyFormat();
    format.setExpandEmptyElements( true );
    format.setTextMode( Format.TextMode.TRIM_FULL_WHITE );

    output.setFormat( format );
    return output.outputString(elem);
}

public static Document createDocument(String xml) throws JDOMException, IOException
{
    InputSource in = new InputSource(new StringReader(xml));
    SAXBuilder saxB = new SAXBuilder();
    return ((saxB.build(in)));
}

public static Element createElement(File xmlFile) throws JDOMException, IOException
{
    SAXBuilder saxB = new SAXBuilder();
    Document document = saxB.build(xmlFile);
    return document.getRootElement();
}


public static void writeXmlFile(Document doc,String path){

    try {
        XMLOutputter xmlOutputer = new XMLOutputter();

        xmlOutputer.setFormat( Format.getPrettyFormat() );
        xmlOutputer.output( doc , new FileWriter( path ) );

    } catch (IOException e) {
       logger.error("cant write xml file",e);
    }
}
}

最佳答案

我们来了

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xml.sax.InputSource;

public class XmlUtils
{
    public static void main(String[] args) throws JDOMException, IOException {
                String test="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><address-book xmlns=\"qwerty\" xmlns:ab2=\"asdfgh\"><contact time-stamp=\"2014-02-26T16:35:20.678+02:00\" id=\"12345\"></contact><contact time-stamp=\"2014-02-26T16:37:19.370+02:00\" id=\"12346\"></contact><contact time-stamp=\"2014-02-26T16:38:53.345+02:00\" id=\"12347\"></contact><contact time-stamp=\"2014-02-26T16:37:30.828+02:00\" id=\"12348\"></contact></address-book>";
        Document document = XmlUtils.createDocument(test);
        Element rootNode=document.getRootElement();
        Namespace namespace=Namespace.getNamespace("qwerty");
        rootNode.setNamespace(namespace);
        List list = rootNode.getChildren("contact",namespace);
        for (int i = 0; i < list.size(); i++) {
              Element node = (Element) list.get(i);
              System.out.println("id values using Style 1 : " + node.getAttribute("id").getValue());
             }
        List<Element> list2 = document.getRootElement().getChildren("contact",namespace);
        for( Element ele : list2){
            System.out.println(ele.getAttribute("id").getValue());
        }
    }
public static String getFormatedXMLString(String doc)  throws JDOMException, IOException
{
    return (  makeDomToFormatedString( createDocument(doc)  ) ) ;
}

public static String makeDomToFormatedString(Document doc)
{
    return makeDomToFormatedString(doc.getRootElement());
}

public static String makeDomToFormatedString(Element elem)
{
    XMLOutputter output = new XMLOutputter();

    Format format = Format.getPrettyFormat();
    format.setExpandEmptyElements( true );
    format.setTextMode( Format.TextMode.TRIM_FULL_WHITE );

    output.setFormat( format );
    return output.outputString(elem);
}

public static Document createDocument(String xml) throws JDOMException, IOException
{
    InputSource in = new InputSource(new StringReader(xml));
    SAXBuilder saxB = new SAXBuilder();
    return ((saxB.build(in)));
}

public static Element createElement(File xmlFile) throws JDOMException, IOException
{
    SAXBuilder saxB = new SAXBuilder();
    Document document = saxB.build(xmlFile);
    return document.getRootElement();
}


public static void writeXmlFile(Document doc,String path){

    try {
        XMLOutputter xmlOutputer = new XMLOutputter();

        xmlOutputer.setFormat( Format.getPrettyFormat() );
        xmlOutputer.output( doc , new FileWriter( path ) );

    } catch (IOException e) {
      e.printStackTrace();
    }
}
}

输出将是

id values using Style 1 : 12345
id values using Style 1 : 12346
id values using Style 1 : 12347
id values using Style 1 : 12348
12345
12346
12347
12348

如果您遇到任何问题,请告诉我:)

关于java - 使用 XmlUtils 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22072714/

相关文章:

java - 解析顶部元素包含对象列表的 XML 文档

php - json 解析失败 - cocoa 错误 3840 和字符 0 周围的无效值

javascript - 解析运算符并在 JavaScript 中评估它们

java - 编译带有嵌套子类的 Java 类突然不起作用, "access denied"

java - JPA:将上次更新时间存储在单独的表中

xml - 将 Excel 的 SUM() 添加到 XLST 结果页?

android - 在 Android manifest 中,如何要求两个硬件中的至少一个?

java - 在 URL 处的 JSON 文件中查找某些字段

java - 尝试从 SSLSocket 读取时获取 EOFException

java - 在 BlackBerry 上解析文本文件需要很长时间