且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在java中将String转换为DOM文档对象?

更新时间:2022-10-16 16:45:12

您可以尝试

  DocumentBuilder db = DocumentBuilderFactory.newInstance()。newDocumentBuilder ); 
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(< root>< nod1>< / node1>< / root>));

文档doc = db.parse(is);

参考这个 http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm


I have a case like getting an XML and convert the XML elements to document object and getting the element values and attributes which i have been created already

Here is the piece of code i have tried to convert the string to DOM document object

String xmlString = " <r><e>d</e></r>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(new InputSource(new StringReader(xmlString)));    
TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result =  new StreamResult(new StringWriter());
transformer.transform(source, result);
String str1 = result.getWriter().toString();
System.out.println(str1);

But this case is valid for only elements without attributes what can we do if the

String xmlString = "<element attribname="value" attribname1="value1"> pcdata</element>"

we are using Double quotes for the attribute values"value". The compiler is showing error

Suggest me if there any xml encoder and decoder is there to handle this scenarios ??

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><nod1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm