我有一个字符串,其内容是XML。我想将标签分开,并使其成为Java中的字符串列表。以下是我正在尝试的东西:
string xml="<hello><hi a='a' b='b'/><hi a='b' b='a'/></hello>";
我想将其分为以下列表:
list[0]="<hi a='a' b='b'/>" list[1]="<hi a='b' b='a'/>"
我试图通过JAXB处理器执行此操作,但效果不佳。还使用split尝试了一些愚蠢的逻辑,但这也无济于事。还有其他方法可以做到这一点吗?
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(); }