java - 将xml节点的所有内容作为字符串 [英] java - Getting all content of a xml node as string

查看:394
本文介绍了java - 将xml节点的所有内容作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码解析xml

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

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

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>

因此,如果想获得< human> as text。

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


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


我怎样才能得到它?

推荐答案

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

这篇关于java - 将xml节点的所有内容作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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