如何在java中将String转换为DOM文档对象? [英] How to convert String to DOM Document object in java?
问题描述
这里是一段代码我尝试将字符串转换为DOM文档对象
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();
变压器变压器= 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);
但是,这种情况仅适用于没有属性的元素
如果
String xmlString =< element attribname =valueattribname1 =value1> pcdata< / element>
我们正在为属性值value使用双引号。编译器显示错误
建议我是否有任何xml编码器和解码器处理这种情况?
您可以尝试
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
这篇关于如何在java中将String转换为DOM文档对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!