Java XML解析复杂的xml文件

时间:2013-12-20 10:07:42

标签: java xml parsing

我真的希望你能帮我这个...... 我需要从我的xml文件中获取特定数据,但我陷入困境,我无法弄清楚如何继续......

我想从网络获取:网络名称;来自代码:mcc和mnc代码;来自设置:名称,ID,类型,参数名称和值;

所以这是我的xml文件的结构:

<country country="Andorra" isoCode="AD">
    <networks>
        <network name="Mobiland" isMNO="true" ranking="10">
            <codes>
                <code mcc="213" mnc="03" />
            </codes>
            <settings>
                <setting alternativeName="Mobiland AD" ref="s1" name="IAP" id="2266" />
                <setting alternativeName="Mobiland MMS AD" ref="s2" name="MMS" id="2265" />
            </settings>
        </network>
    </networks>
    <settings>
        <setting id="s2" type="mmssetting">
            <parameter name="mms-gprs-access-point-name" value="MMS" />
            <parameter name="mms-gprs-name" value="MMS" />
            <parameter name="mms-gprs-proxy" value="192.168.021.050" />
            <parameter name="mms-gprs-proxy-port" value="9201" />
            <parameter name="mms-url" value="http://mms.ad/mmsc" />
        </setting>
        <setting id="s1" type="iapsetting">
            <parameter name="iap-gprs-access-point-name" value="internet" />
            <parameter name="iap-gprs-name" value="Internet" />
            <parameter name="iap-gprs-url" value="http://google.com" />
        </setting>
    </settings>
</country>

这就是我到目前为止......我真的无法继续......我在String content = cNode.getLastChild()时有一个空指针异常.getTextContent()。trim( );而且我不确定我是以正确的方式做到这一点......

public void ReadXML()抛出ParserConfigurationException,SAXException,             IOException {

    // Get the DOM Builder Factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Get the DOM Builder
    DocumentBuilder builder = factory.newDocumentBuilder();

    // Load and Parse the XML document
    // document contains the complete XML as a Tree.
    Document document = builder.parse("D:\\test.xml");

    List<Apn> empList = new ArrayList<Apn>();

    // Iterating through the nodes and extracting the data.
    NodeList nodeList = document.getDocumentElement().getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {

        Node node = nodeList.item(i);
        if (node instanceof Element) {
            //Apn apn = new Apn();
            System.out.println(node.getAttributes().getNamedItem("country")
                    .getNodeValue());

            NodeList childNodes = node.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node cNode = childNodes.item(j);


                if (cNode instanceof Element) {
                    String content = cNode.getLastChild().getTextContent()
                            .trim();

                    switch (cNode.getNodeName()) {
                    case "networks":
                        System.out.println(content);
                        break;
                    case "setting":
                        System.out.println(content);
                        break;
                    case "codes":
                        System.out.println(content);
                        // emp.location = content;
                        break;
                    }
                }
            }

        }

    }
}

任何帮助都会被暗示!

谢谢!

3 个答案:

答案 0 :(得分:2)

使用XPath。例如,要获取name元素的network属性的值,您可以执行以下操作:

InputStream is = this.getClass().getResourceAsStream("country.xml");
InputSource inputSource = new InputSource(is);

XPath xpath = XPathFactory.newInstance().newXPath();

String expression = "/country/networks/network/@name";
NodeList names = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);
for (int i = 0; i < names.getLength(); i++) {
  System.out.println(names.item(i).getNodeValue());
}

输出:

Mobiland

答案 1 :(得分:1)

我认为处理这种复杂xml结构的最简单方法是编写xsd schema并使用JAXB

将xml转换为java对象

答案 2 :(得分:0)

您可以使用Declarative Stream Mapping (DSM)流解析库轻松地将复杂的xml转换为java类。 DSM具有非常强大的映射结构和脚本支持

首先,您必须以yaml格式定义xml数据和类字段之间的映射。

以下是XML的映射定义。

result:     
   type: object
   path: /country       
   fields:
       network:          
          type: array
          path: networks/network
          fields:       
             name: 
               xml: 
                 attribute: true                 
             codes:
               type: array
               path: codes/code
               fields:
                 mcc:
                   xml:
                     attribute: true
                 mnc:
                   xml:
                     attribute: true                      
       settings:
          type: array
          path: settings/setting
          fields:       
             id: 
               xml:
                 attribute: true
             type: 
               xml:
                 attribute: true
             parameter:
               type: array
               fields:
                 name:
                   xml:
                     attribute: true
                 value:
                   xml:
                     attribute: true

用于解析XML的Java代码:

DSM dsm=new DSMBuilder(new File("path/to/mapping.yaml")).setType(DSMBuilder.TYPE.XML).create();
Object object =  dsm.toObject(xmlFileContent);
dsm.getObjectMapper().writerWithDefaultPrettyPrinter().writeValue(System.out, object)

这是输出的json表示形式:

{
  "network" : [ {
    "name" : "Mobiland",
    "codes" : [ {
      "mcc" : "213",
      "mnc" : "03"
    } ]
  } ],
  "settings" : [ {
    "id" : "s2",
    "type" : "mmssetting",
    "parameter" : [ {
      "name" : "mms-gprs-access-point-name",
      "value" : "MMS"
    }, {
      "name" : "mms-gprs-name",
      "value" : "MMS"
    }, {
      "name" : "mms-gprs-proxy",
      "value" : "192.168.021.050"
    }, {
      "name" : "mms-gprs-proxy-port",
      "value" : "9201"
    }, {
      "name" : "mms-url",
      "value" : "http://mms.ad/mmsc"
    } ]
  }, {
    "id" : "s1",
    "type" : "iapsetting",
    "parameter" : [ {
      "name" : "iap-gprs-access-point-name",
      "value" : "internet"
    }, {
      "name" : "iap-gprs-name",
      "value" : "Internet"
    }, {
      "name" : "iap-gprs-url",
      "value" : "http://google.com"
    } ]
  } ]
}