使用XmlUtils解析XML

时间:2014-02-27 15:18:04

标签: java xml parsing jdom

我正在使用XmlUtils来解析和提取List中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());
}

Class 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);
    }
}
}

1 个答案:

答案 0 :(得分:0)

我们走了

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

让我知道你是否面临任何问题:)