[英]java convert xml String to List<String>
我想将作为 XML 的字符串转换为列表。
逻辑必须是通用的。 只应将记录的 XPath 作为输入。 有时这可以是任何类型的数据。
我尝试了互联网帮助,但无法获得对 XML 解析新的通用解决方案。
输入字符串
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description>
</book>
</catalog>
需要输出列表
List<String> x = some logic to get all books with each book in one String;
for(i=0;i<x.length;i++){
System.out.println("element number "+ i)
System.out.println(x[i])
}
element number 0
<book id="bk101">
<author>Gambardella, Matthew</author>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
element number 1
<book id="bk102">
<author>Ralls, Kim</author>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
</book>
.
.
.
.
您可以将字符串转换为 xml 文档并提取节点
String xmlString = ...;
String nodeName = "book";
List<String> nodeStrList = getNodeStringList(xmlString, nodeName);
for(int i = 0; i < nodeStrList.size(); i++){
System.out.println("element number "+ i);
System.out.println(nodeStrList.get(i));
}
此方法进行所有转换,您将获得所需的输出
public List<String> getNodeStringList(String xmlString, String nodeName) {
List<String> nodeStrList = new ArrayList<>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xmlString)));
NodeList nodeList = doc.getDocumentElement().getElementsByTagName(nodeName);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
for (int count = 0; count < nodeList.getLength(); count++) {
Node node = nodeList.item(count);
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(node), new StreamResult(writer));
nodeStrList.add(writer.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return nodeStrList;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.