开发者

java - Getting all content of a xml node as string

开发者 https://www.devze.com 2023-03-16 22:32 出处:网络
I am using this code to parsing xml DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

I am using this code to parsing xml

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(data));
    Document doc = db.parse(is);

Now I want to get all content from a xml node. Like from this xml

<?xml version='1.0'?>开发者_开发知识库
<type>
  <human>                     
    <Name>John Smith</Name>              
    <Address>1/3A South Garden</Address>    
  </human>
</type>

So if want to get all content of <human> as text.

<Name>John Smith</Name>
<Address>1/3A South Garden</Address>

How can I get it ?


private String nodeToString(Node node) {
  StringWriter sw = new StringWriter();
  try {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.transform(new DOMSource(node), new StreamResult(sw));
  } catch (TransformerException te) {
    System.out.println("nodeToString Transformer Exception");
  }
  return sw.toString();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消