我正在构建一个与 Web 服务器通信的 Android 应用程序,并且遇到以下情况:
给定字符串中的一行 XML,例如:
"<test one="1" two="2" />"
我想将值提取到 HashMap 中,以便:
map.get("one") = "1"
map.get("two") = "2"
我已经可以使用 SAX 解析器对完整的 XML 文档执行此操作,当我尝试将上面的字符串与 MalformedUrlException 一起提供时,它会提示:未找到协议(protocol)
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc = null;
builder = factory.newDocumentBuilder();
doc = builder.parse("<test one="1" two="2" />"); //here
我知道一些正则表达式可以做到这一点,但我真的更愿意正确地做到这一点。
可以在 http://metacpan.org/pod/XML::Simple#XMLin 找到相同的行为这是 Web 服务器使用的内容。
有人可以帮忙吗?谢谢:D
最佳答案
DocumentBuilder.parse(String)
将字符串视为 URL。试试这个:
Document doc = builder.parse(new InputSource(new StringReader(text)));
(当然,text
包含 XML)。
关于java - 将单行 XML 解析为 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7286807/