简体   繁体   中英

How to get XML content as a String

<root>
<h id="1">
    <d value="1,2,3,4,5"><open>10:00</open><close>23:00</close></d>
    <d value="6"><open>10:00</open><close>2:00</close></d>
    <d value="7"><open>10:00</open><close>21:00</close></d>
</h>
<h id="2">
</h>
</root>

Here I have the XML which root has list of <h> tagged nodes. Now I need to break these into parts and set it into different variables (add into a map).

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(data.getBytes("utf-8"))));
NodeList nList = doc.getElementsByTagName("h");
for (int i = 0; i < nList.getLength(); i++)
{
    Node nNode = nList.item(i);
    System.out.println(nNode.getAttributes().getNamedItem("id") + " " + ?????);        
}

what should I call in order to get the value ( String value ) of a nNode ?

Here is what Im looking for as the asnwer for the above code once some one fills the ????

1 <h id="1"><d value="1,2,3,4,5"><open>10:00</open><close>23:00</close></d><d value="6">open>10:00</open><close>2:00</close></d><d value="7"><open>10:00</open><close>21:00</close></d></h>
2 <h id="2"></h>

And i don't mind having as root element

You can use Node.getTextContent() to conveniently get all the text of a node (gets text of children as well).

See Parsing xml file contents without knowing xml file structure for a short example.


If you're trying to get the value attributes of the d nodes (I can't actually tell, your question is slightly unclear to me), then it would be different -- for that you would iterate through the children of each h node (use getChildNodes() or getFirstChild() + getNextSibling() ) then grab their value attributes just as you are getting the id attribute of the h nodes (the above link also shows an example of iterating through child nodes).

Have you tried jDom library? http://www.jdom.org/docs/apidocs/org/jdom2/output/XMLOutputter.html

 XMLOutputter outp = new XMLOutputter();
 String s = outp.outputString(your_jdom_element);

如果您使用的是来自javax.xml.soap.Node Node,您是否尝试过nNode.toString()

You can use that:

http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getTextContent()

but your sample nNode has other nodes, not just text. It seems you need helper method to construct String from child nodes.

Pass your nNode to nodeToString

XML Node to String in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM