Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

xml - How to convert String to DOM Document object in java?

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 ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can try

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

Document doc = db.parse(is);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...