예제 #1
0
  //	@Test
  public void testElementsByTagNameWithNamespace() throws Exception {
    builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);

    String xml =
        "<?xml version=\"1.0\"?>"
            + "<t:root xmlns=\"http://void.com/\" xmlns:t=\"http://t.com/\" id=\"stella\" t:type=\"police\">"
            + "<t:item id=\"a\"/>"
            + "<child id=\"1\"/>"
            + "<t:item id=\"b\"/>"
            + "<child id=\"2\"/>"
            + "</t:root>";

    // TODO: Can I utilize xmlSearchNs or xmlSearchNsByHref? the problem is it searchs a specific
    // node and recurse up.
    // I don't have such a node

    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
    Element root = doc.getDocumentElement();

    List<String> expectedList = Arrays.asList("1", "2");
    List<String> actualList = new ArrayList<String>();
    NodeList nl = root.getElementsByTagNameNS("http://void.com/", "child");
    for (int i = 0; i < nl.getLength(); i++) {
      Element elem = (Element) nl.item(i);
      actualList.add(elem.getAttribute("id"));
    }
    Assert.assertArrayEquals("elementsByTagName", expectedList.toArray(), actualList.toArray());

    expectedList = Arrays.asList("a", "b");
    actualList.clear();
    nl = root.getElementsByTagNameNS("http://t.com/", "item");
    for (int i = 0; i < nl.getLength(); i++) {
      Element elem = (Element) nl.item(i);
      actualList.add(elem.getAttribute("id"));
    }
  }