java 如何将字符串转换为xml

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

How to convert string to xml

javaxml

提问by yogsma

I have a string which contains XML data and I want to convert it to XML document object. How do I do that?

我有一个包含 XML 数据的字符串,我想将其转换为 XML 文档对象。我怎么做?

回答by Preet Sangha

say theString holds the XML,

说 theString 保存了 XML,

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(theString)));

More info here

更多信息在这里

回答by John McCloskey

All you have to do is pass the string to the LoadXml method of the XmlDocument class. Then, you can use XPath to get the values of the elements/attributes in the document.

您所要做的就是将字符串传递给 XmlDocument 类的 LoadXml 方法。然后,您可以使用 XPath 获取文档中元素/属性的值。

回答by flash

You could use several libraries to do this.

您可以使用多个库来执行此操作。

If you have a schema file for the XML you could use JAXBto do this. If you have no schema file you better stick with libraries like JDOMor SAXON.

如果您有 XML 的模式文件,您可以使用JAXB来执行此操作。如果您没有模式文件,您最好坚持使用JDOMSAXON 之类的库。