我想在java中将XML字符串转换为Document。代码如下..
package org.com;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class MainPage {
public static void main(String[] args)
{
final String xmlStr = "<employees>" +
" <employee id=\"101\">" +
" <name>Lokesh Gupta</name>" +
" <title>Author</title>" +
" </employee>" +
" <employee id=\"102\">" +
" <name>Brian Lara</name>" +
" <title>Cricketer</title>" +
" </employee>" +
"</employees>";
//Use method to convert XML string content to XML Document object
Document doc = convertStringToXMLDocument( xmlStr);
doc.getDocumentElement().normalize();
//Verify XML document is build correctly
System.out.println(doc.getFirstChild().getNodeName());
}
private static Document convertStringToXMLDocument(String xmlString)
{
//Parser that produces DOM object trees from XML content
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//API to obtain DOM Document instance
DocumentBuilder builder;
try
{
//Create DocumentBuilder with default configuration
builder = factory.newDocumentBuilder();
//Parse the content to Document object
Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
return doc;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
但是当我尝试调试这段代码时Document
像这样显示 null .. [#document: null]
。
这里的问题是如何转换XML
字符串仅位于 Document
中不使用 Nodelist
的对象逐一读取子节点。
我提到了这个Example
请帮忙..
提前致谢
最佳答案
1,我的例子使用jdom 2,喜欢这段代码
final String xmlStr = "<employees>" +
" <employee id=\"101\">" +
" <name>Lokesh Gupta</name>" +
" <title>Author</title>" +
" </employee>" +
" <employee id=\"102\">" +
" <name>Brian Lara</name>" +
" <title>Cricketer</title>" +
" </employee>" +
"</employees>";
StringReader stringReader = new StringReader(xmlStr);
SAXBuilder builder = new SAXBuilder();
Document build = builder.build(stringReader);
Element rootElement = build.getRootElement();
List employee = rootElement.getChildren();
for (int i = 0; i < employee.size(); i++) {
Element emp = (Element) employee.get(i);
String id = emp.getAttributeValue("id");
String name = emp.getChildText("name");
String title = emp.getChildText("title");
System.out.printf("id: %s,name: %s, title : %s", id, name, title);
System.out.println();
}
关于java - 使用java将XML字符串转换为文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451562/