我昨天问过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&b=2&c=3</post_body>
关于java - 无法从 XML 文件读取 <post_body> 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578681/