我有一个案例,比如获取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>"
我们使用双引号作为属性值“value”。编译器显示错误
建议我是否有任何xml编码器和解码器来处理这种情况?
答案 0 :(得分:45)
你可以尝试
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
答案 1 :(得分:6)
使用\
String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"
或改为使用单引号
String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"
答案 2 :(得分:2)
public static void main(String[] args) {
final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
"<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
"<role>Developer</role><gen>Male</gen></Emp>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) );
} catch (Exception e) {
e.printStackTrace();
}
}
答案 3 :(得分:2)
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
即使XML结构很复杂,这对我也很有用。
请确保您的xmlString对XML有效,请注意转义字符应在前面添加“\”。
主要问题可能不是来自属性。