java - 将 xml 节点的所有内容作为字符串获取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6534182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:14:38  来源:igfitidea点击:

java - Getting all content of a xml node as string

javaxml

提问by Barun

I am using this code to parsing xml

我正在使用此代码来解析 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 节点获取所有内容。喜欢从这个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.

所以如果想获取<human>文本的所有内容。

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

How can I get it ?

我怎么才能得到它 ?

回答by Rupok

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