解析XML字符串并构建字符串列表 [英] Parse XML string and build a list of strings

查看:73
本文介绍了解析XML字符串并构建字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其内容是XML。我想分隔标签并将其变成Java中的字符串列表。以下是我正在尝试的内容:

I have a string whose content is an XML. I want to separate the tags and make it into a list of string in Java. Below is a something what I am trying:

string xml="<hello><hi a='a' b='b'/><hi a='b' b='a'/></hello>";

我想把它分成如下列表:

I want to separate it into a list like:

list[0]="<hi a='a' b='b'/>"
list[1]="<hi a='b' b='a'/>"

我试图通过JAXB处理器执行此操作,但效果不佳。还尝试了一些使用拆分的愚蠢逻辑,但这也无济于事。有没有其他方法可以达到这个目的?

I tried to do this via JAXB processor but doesn't work well. Also tried some stupid logic using split but that didn't help either. Is there any other way to achieve this?

推荐答案

string xml="<hello><hi a='a' b='b'/><hi a='b' b='a'/></hello>";

//read XML from the given string
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);

//this will return a list of xml tags whose name is `hi`
NodeList hiList = document.getElementsByTagName("hi");

//you can iterate over hiList and read/process them
for (int i = 0; i < hiList.getLength(); i++) {
    Node child = hiList.item(i);
    String name = child.getNodeName();
    String contents = child.getTextContent();
}

这篇关于解析XML字符串并构建字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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