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

2022-09-03 17:54:23

我正在使用此代码来解析xml

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

现在我想从 xml 节点获取所有内容。像从这个xml

<?xml version='1.0'?>
<type>
  <human>                     
    <Name>John Smith</Name>              
    <Address>1/3A South Garden</Address>    
  </human>
</type>

所以如果想把所有内容都做成文本。<human>

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

我怎样才能得到它?


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

答案 2

推荐