简体   繁体   English

将简单的XML文档从URL解析为String变量

[英]Parse simple XML document from URL to String variable

I am attempting to read XML from a server on http://localhost:8000 , into a string variable. 我正在尝试从http:// localhost:8000上的服务器读取XML到字符串变量中。

The layout of the XML document is very simple, and when directing to http://localhost:8000 , the following is displayed: XML文档的布局非常简单,当指向http:// localhost:8000时 ,将显示以下内容:

<result>Hello World</result>

Is there a simple way to parse this into a String variable from the localhost URL, so that for example, if I was to run: 有没有一种简单的方法可以将其从localhost URL解析为String变量,例如,如果我要运行:

System.out.println(XMLVariable) 

(where XMLVariable is the string variable in which the content was stored in) that the output to the command line would simply be "Hello World"? (其中XMLVariable是存储内容的字符串变量),命令行的输出将仅仅是“ Hello World”?

You need to parse the response from the server into an XML data structure of some sort. 您需要将来自服务器的响应解析为某种XML数据结构。

The easiest way that I'm aware of (in Java) to do that is to use dom4j . 我知道(在Java中)最简单的方法是使用dom4j

It can be as simple as this... 可以这么简单...

SAXReader reader = new SAXReader();
Document document = reader.read("http://localhost:8000/");
System.out.println(document.getText());

You can use StAX for parsing the response: 您可以使用StAX来解析响应:

private Optional<String> extractResultValue(String xml) throws XMLStreamException {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    final XMLEventReader reader = factory.createXMLEventReader(new StringReader(xml));
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isCharacters()) {
            return Optional.ofNullable(event.asCharacters().getData());
        }
    }
    return Optional.empty();
}

Example call: 示例调用:

extractResultValue("<Your data from server>")
extractResultValue("<result>Hello World</result>") // Optional[Hello World]
extractResultValue("<result></result>") // Optional.empty
extractResultValue("<test>value</test>") // Optional[value]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM