我有一个具有重复节点的XML,并使用DOM解析器对其进行顶层解析。经过大量的研发,我可以在网上找到任何可以帮助我的东西。我的xml看起来像
<nos1>
<Name>aqwer</Name>
<class>sas</class>
<class>xcd</class>
<class>asd</class>
<Name>cfg</Name>
<Name>cfg</Name>
<nos1>任何建议,我如何能够解析这个xml的重复值。
发布于 2014-12-22 06:58:20
您可以使用XML文档解析w3c,如下所示:
DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = df.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(response.getContent().getBytes("UTF-8"));
org.w3c.dom.Document doc = db.parse(is);
NodeList links = doc.getElementsByTagName("class");
for(int i=0; i< links.getLength(); i++)
{
Node link = links.item(i);
System.out.println(link.getTextContent());
}
}
catch(Exception ex)
{
}希望这能帮到你。
发布于 2014-12-22 08:23:57
您应该读取所有元素,并在阅读之后,通过一组消除重复项。下面是一个使用XMLBeam的示例,但是任何其他库都可以。
public class TestMultipleElements {
@XBDocURL("resource://test.xml")
public interface Projection {
@XBRead("/nos1/Name")
List<String> getNames();
@XBRead("/nos1/class")
List<String> getClasses();
}
@Test
public void uniqueElements() throws IOException {
Projection projection = new XBProjector().io().fromURLAnnotation(Projection.class);
for (String name : new HashSet<String>(projection.getNames())) {
System.out.println("Found Name:" + name);
}
for (String clazz : new HashSet<String>(projection.getClasses())) {
System.out.println("Found Name:" + clazz);
}
}
}这张打印出来:
Found Name:aqwer
Found Name:cfg
Found Name:xcd
Found Name:sas
Found Name:asdhttps://stackoverflow.com/questions/27597545
复制相似问题