在 Java 中将 XML 块提取为字符串 [英] Extract XML blocks as string in Java

查看:37
本文介绍了在 Java 中将 XML 块提取为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的 XML

I have an XML as below

<accountProducts>
 <accountProduct>...</accountProduct>
 <accountProduct>...</accountProduct>
 <accountProduct>...</accountProduct>
 <accountProduct>...</accountProduct>
</accountProducts>

现在我想将每个 accountProduct 块提取为字符串.那么是否有任何 XML 解析技术可以做到这一点,或者我需要进行字符串操作.

Now I want to extract each of the accountProduct block as string. So is there any XML parsing technique to do that or I need to do string manipulation.

请提供任何帮助.

推荐答案

按照上面的建议使用 DOM,您需要使用 DocumentBuilder 解析 XML.

Using the DOM as suggested above, you will need to parse your XML with a DocumentBuilder.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//if your document has namespaces, you can specify that in your builder.
DocumentBuilder db = dbf.newDocumentBuilder();

Using this object, you can call the parse() method.

您的 XML 输入可以作为文件或流提供给 DOM 解析器.

Your XML input can be provided to a DOM parser as a file or as a stream.

作为文件...

File f = new File("MyXmlFile.xml");
Document d = db.parse(f);

作为字符串...

String myXmlString = "...";
InputSource ss = new InputSource(new StringReader(myXmlString));
Document d = db.parse(ss);

一旦有了 Document 对象,就可以使用 DOM 函数或 XPATH 遍历文档.此示例说明了 DOM 方法.

Once you have a Document object, you can traverse the document with DOM functions or with XPATH. This example illustrates the DOM methods.

在您的示例中,假设 accountProduct 节点仅包含文本,以下应该可以工作.

In your example, assuming that accountProduct nodes contain only text, the following should work.

NodeList nl = d.getElementsByTagName("accountProduct");
for(int i=0; i<nl.getLength(); i++) {
    Element elem = (Element)nl.item(i);
    System.out.println(elem.getTextContent());
}

如果 accountProduct 包含混合内容(文本和元素),您将需要更多代码来提取您需要的内容.

If accountProduct contains mixed content (text and elements), you would need more code to extract what you need.

这篇关于在 Java 中将 XML 块提取为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆