Java 中的 XML 节点到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4412848/
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-08-14 17:12:07  来源:igfitidea点击:

XML Node to String in Java

javaxml

提问by Kevin

I came across this piece of Java function to convert an XML node to a Java String representation:

我遇到了这段将 XML 节点转换为 Java 字符串表示的 Java 函数:

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

It looks straightforward in that it wants the output string doesn't have any XML declaration and it must contain indentation.

它看起来很简单,因为它希望输出字符串没有任何 XML 声明并且它必须包含缩进。

But I wonder how the actual output should be, suppose I have an XML node:

但我想知道实际输出应该如何,假设我有一个 XML 节点:

<p><media type="audio" id="au008093" rights="wbowned">
<title>Bee buzz</title>
</media>Most other kinds of bees live alone instead of in a colony. These bees make
        tunnels in wood or in the ground. The queen makes her own nest.</p>

Could I assume the resulting String after applying the above transformation is:

我可以假设应用上述转换后的结果字符串是:

"media type="audio" id="au008093" rights="wbowned" title Bee buzz title /media"

I want to test it myself, but I have no idea on how to represent this XML node in the way this function actually wants.

我想自己测试它,但我不知道如何以这个函数实际想要的方式来表示这个 XML 节点。

I am bit confused, and thanks in advance for the generous help.

我有点困惑,在此先感谢您的慷慨帮助。

采纳答案by Cratylus

You have an XML respesentation in a DOM tree.
For example you have opened an XML file and you have passed it in the DOM parser.
As a result a DOM tree in memory with your XML is created.
Now you can only access the XML info via traversal of the DOM tree.
If you need though, a String representation of the XML info of the DOM tree you use a transformation.
This happens since it is not possible to get the String representation directly from a DOM tree.
So if for example as Node nodeyou pass in nodeToStringis the root element of the XML doc then the result is a String containing the original XML data.
The tags will still be there. I.e. you will have a valid XML representation. Only this time will be in a String variable.

您在 DOM 树中有一个 XML respesentation。
例如,您打开了一个 XML 文件,并在 DOM 解析器中传递了它。
结果是在内存中创建了一个带有 XML 的 DOM 树。
现在您只能通过遍历 DOM 树来访问 XML 信息。
如果需要,您可以使用转换的 DOM 树的 XML 信息的字符串表示。
发生这种情况是因为无法直接从 DOM 树获取 String 表示。
因此,例如,如果Node node您传入的nodeToString是 XML 文档的根元素,则结果是一个包含原始 XML 数据的字符串。
标签仍然存在。即您将有一个有效的 XML 表示。只有这一次将在 String 变量中。

For example:

例如:

  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder parser = factory.newDocumentBuilder();
  Document xmlDoc = parser.parse(file);//file has the xml
  String xml = nodeToString(xmlDoc.getDocumentElement());//pass in the root
  //xml has the xml info. E.g no xml declaration. Add it
  xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> + xml;//bad to append this way...
  System.out.println("XML is:"+xml);

DISCLAIMER:Did not even attempt to compile code. Hopefully you understand what you have to do

免责声明:甚至没有尝试编译代码。希望你明白你必须做什么

回答by Jiri Patera

All important has already been said. I tried to compile the following code.

重要的都说了。我试图编译以下代码。


import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class Test {

  public static void main(String[] args) throws Exception {

    String s = 
      "<p>" +
      "  <media type=\"audio\" id=\"au008093\" rights=\"wbowned\">" +
      "    <title>Bee buzz</title>" +
      "  " +
      "  Most other kinds of bees live alone instead of in a colony." +
      "  These bees make tunnels in wood or in the ground." +
      "  The queen makes her own nest." +
      "</p>";
    InputStream is = new ByteArrayInputStream(s.getBytes());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse(is);

    Node rootElement = d.getDocumentElement();
    System.out.println(nodeToString(rootElement));

  }

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

}

And it produced the following output:

它产生了以下输出:


<p>  <media id="au008093" rights="wbowned" type="audio">    <title>Bee buzz</title>  </media>  Most other kinds of bees live alone instead of in a colony.  These bees make tunnels in wood or in the ground.  The queen makes her own nest.</p>

You can further tweak it by yourself. Good luck!

您可以自己进一步调整它。祝你好运!