Java:解析XML并将所有数据内容绑定到Map< K,V>. [英] Java: Parse XML and bind all data content to a Map <K, V>

查看:328
本文介绍了Java:解析XML并将所有数据内容绑定到Map< K,V>.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发SOAP客户端&特定于我们项目的解析器.我已经完成了客​​户端,它会调用多种(几种不同的)SOAP Web服务并以XML格式获取响应SOAP消息.

I'm trying to develop a SOAP client & parser which is specific to our project. I've already finished the client and it invokes many kinds of (several different) SOAP web services and getting response SOAP message in XML format.

我的目标:

从任何类型的集合中获取任何节点或属性的值,并且该值应用于我的所有Web服务响应.

Get the value of any node or attribute from any type of collection and it should be worked for all of my web services responses.

例如,我会这样称呼:

String h1 = collection.get("html/body/h1");

,h1的值应为"StackOverflow",并来自:

and h1's value should be 'StackOverflow' and come from:

<html>
  <head></head>
  <body>
    <h1>StackOverflow</h1>
    <p>XML parsing in Java</p>
  </body>
</html>

我的方法:

现在我收到响应消息.我想解析它,并将所有节点(和属性)的值分配给一个集合(映射),并从该集合中获取数据.集合的(Map) key 将是节点的路径,而 value 将是节点或属性的值.

Now i have the response message. I want to parse it and assign all the node (and attribute) values to a collection (map) and get data from that collection. The collection's (Map ) key would be the path of node and the value would be the node's or attribute's value.

例如

<MethodResponse xmlns="any.xmlns">
    <MethodResult>any value</MethodResult>
    <Node1>
        <Node2>
            <Node3>
                node3 value is here
            <Node3>
        </Node2>
    </Node1>
    <respCode>99</respCode>
    <respNote>any value</respNote>
</MethodResponse>

如果我需要在这里输入respCode,我可以通过这种方式调用它:

If i need to respCode in here, i would be able to call that in this way:

String respCode = map.get("/MethodResponse/respCode");

或到Node3:

String node3Value = map.get("/MethodResponse/Node1/Node2/Node3");

就像XPath.但是我不想任何映射或任何Java类.我只想从其路径访问节点(或属性)值.

like as XPath. But i don't want to any mapping or any Java class. I just want to access nodes (or attributes) value from its path.

成功条件:

它适用于以下以及几种不同的SOAP消息:

It works for these and several different SOAP messages:

  • http://www.w3schools.com/xml/note.xml
  • http://www.w3schools.com/xml/cd_catalog.xml
  • http://www.w3schools.com/xml/simple.xml
  • http://msdn.microsoft.com/en-us/library/ms762271%28v=vs.85%29.aspx

我的问题:

  1. 我的方法正确吗?
  2. 如果是,我该怎么做?有任何有效的代码或教程吗?
  3. 如果没有,我该怎么办?

推荐答案

创建Java DOM XML解析器是使用javax.xml.parsers.DocumentBuilderFactory类完成的.这是一个示例:

Creating a Java DOM XML parser is done using the javax.xml.parsers.DocumentBuilderFactory class. Here is an example:

DocumentBuilderFactory builderFactory =
        DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
    builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
    e.printStackTrace();  
}

使用DocumentBuilder将XML文件解析为DOM树是这样的:

Parsing an XML file into a DOM tree using the DocumentBuilder is done like this:

try {
    Document document = builder.parse(
            new FileInputStream("data\\text.xml"));
} catch (SAXException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

顶部是Document对象. Document对象只有一个根元素,可以通过调用getDocumentElement()来返回该元素,如下所示:

At the top is the Document object. The Document object has a single root element, which is returned by calling getDocumentElement() like this:

Element rootElement = document.getDocumentElement();

获取元素的子元素

NodeList nodes = element.getChildNodes();

for(int i=0; i<nodes.getLength(); i++){
  Node node = nodes.item(i);

  if(node instanceof Element){
    //a child element to process
    Element child = (Element) node;
    String attribute = child.getAttribute("width");
  }
}

现在您有了一个需要的Node,因此您可以根据需要创建将其放置在map中,并需要您输入密钥.方法transformer.transform(新的DOMSource(文档),可与任何Dom节点或元素一起使用

Now you have a needed Node, so you can create put it in map as you wish, and make need for you key. method transformer.transform(new DOMSource(document),work with any Dom node or element

从文档创建字符串

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(document),
      new StreamResult(buffer));
String str = buffer.toString();

这篇关于Java:解析XML并将所有数据内容绑定到Map&lt; K,V&gt;.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆