我问了yersterday this问题。现在,我在使用类似的XML文件时遇到了问题。我的问题是,它读起来一直很好,直到“ post_body”为止。在starElement中发送消息时确实会找到它,但无法打印此标记的上下文。
这是为什么 ?我也被建议在endDocument()中打印s,但似乎不起作用。这又是我的XML文件和代码:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <data>
      <track clipid="1">
         <url>http://www.emp3world.com/to_download.php?id=33254</url>
         <http_method>GET or POST</http_method>
         <post_body>a=1&b=2&c=3</post_body>
      </track>
   </data>
</root>


码:

class MyHandler extends DefaultHandler
{
    String str = "";
    StringBuilder s = new StringBuilder();
    public void startElement(String namespaceURI, String sName, String qName, Attributes atts)
    {

        s.setLength(0);

        if(qName.equals("track"))
        {
            s.append("ID: ").append(atts.getValue("clipid")).append("\n");
        }
        if(qName.equals("url"))
        {
            s.append("URL: ");
        }
        if(qName.equals("http_method"))
        {
            s.append("Http method: ");
        }
        if(qName.equals("header"))
        {
            s.append("Header: ");
        }
        if(qName.equals("post_body"))
        {
            s.append("Post body: ");
        }
    }

    public void endElement(String uri, String localName, String qName)
    {
        System.out.println(s);
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        s.append(new String(ch, start, length));
    }
}

最佳答案

这是无效的XML:

<post_body>a=1&b=2&c=3</post_body>


&符号未正确编码,因此此文件格式错误且无效,并且XML解析器不会读取它。

它应该是

<post_body>a=1&amp;b=2&amp;c=3</post_body>

09-10 06:31
查看更多