java将字符串转换为xml文档

时间:2016-06-06 09:51:52

标签: java

我有包含url的text属性的字符串。 这是样本

<xml><body>
<TextView
width="wrap_content"
height="wrap_content"
text="http://www.hello.com/getpage.doappLinkName=checkworkflow&viewLinkName=na"
textColor="#000000"
textSize="14dp"
margin="0,6,0,0"
/>
</body></xml>

当我将此字符串转换为xml文档时,我得到此异常java.net.MalformedURLException:no protocol:

这是代码

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder=docBuilderFactory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlStr));
Document xmlDoc = builder.parse(is);

我认为它是文本属性中的url的bcoz。 如何将其转换为xml文档?

1 个答案:

答案 0 :(得分:1)

xml中不允许使用&符号。您必须将其编码为&amp;

...getpage.doappLinkName=checkworkflow&viewLinkName...    

变为

...getpage.doappLinkName=checkworkflow&amp;viewLinkName...

样品:

public void test() throws ParserConfigurationException, SAXException, IOException {
    String xml = "<xml><body>\n"
            + "<TextView\n"
            + "width=\"wrap_content\"\n"
            + "height=\"wrap_content\"\n"
            + "text=\"http://www.hello.com/getpage.doappLinkName=checkworkflow&amp;viewLinkName=na\"\n"
            + "textColor=\"#000000\"\n"
            + "textSize=\"14dp\"\n"
            + "margin=\"0,6,0,0\"\n"
            + "/>\n"
            + "</body></xml>";
    DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
    DocumentBuilder bldr = fctr.newDocumentBuilder();
    InputSource insrc = new InputSource(new StringReader(xml));
    Document data = bldr.parse(insrc);
    System.out.println("data:" + data);
}