如何在java中将字符串转换为DOM文档对象?

2022-09-01 11:23:18

我有一个案例,比如获取XML并将XML元素转换为文档对象,并获取我已经创建的元素值和属性

这是我尝试将字符串转换为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(); 
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);

但是这种情况只对没有属性的元素有效,如果

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

我们使用双引号作为属性值“值”。编译器显示错误

建议我,如果有任何xml编码器和解码器有处理这种情况??


答案 1

你可以试试

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

Document doc = db.parse(is);

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


答案 2

要么用\

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

或改用单引号

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