2015-09-08 1 views
1

Вот мой XML-файлКак игнорировать родительский узел файла XML в Java

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?> 
<hierarchy rotation="0"> 
    <node class="A"> 
     <node class="B"/> 
     <node class="C"/> 
     <node class="D"/> 
    </node> 
</hierarchy> 

Может кто-нибудь сказать мне код Java, чтобы игнорировать узел с class="A"? Я просто хочу, чтобы дочерние узлы заканчивались /> и читали их значения атрибутов. Я использую класс DocumentBuilderFactory в java для вышеуказанного сценария.

+0

рассматривать только те элементы, которые не имеют ни одного ребенка. –

+0

Но как я даже пробовал (! (NodeObject.hasChildNodes())), но его не работает –

ответ

0

Это будет делать это:

public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException { 
    final String xmlString = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>" 
    + "<hierarchy rotation=\"0\">" 
    + "<node class=\"A\">" 
    + "<node class=\"B\"/>" 
    + "<node class=\"C\"/>" 
    + "<node class=\"D\"/>" 
    + "</node>" 
    + "</hierarchy>"; 

    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
    final InputSource inputSource = new InputSource(new StringReader(xmlString)); 
    final Document document = documentBuilder.parse(inputSource); 
    final NodeList childNodes = document.getFirstChild().getFirstChild().getChildNodes(); 

    for (int i = 0; i < childNodes.getLength(); i++) { 
     final Node childNode = childNodes.item(i); 
     System.out.println("childNode[" + i + "].getAttributes(): " + toStringAttributes(childNode)); 
    } 
} 

private static String toStringAttributes(Node childNode) { 
    String attributesString = "["; 
    final NamedNodeMap attributes = childNode.getAttributes(); 

    for (int i = 0; i < attributes.getLength(); i++) { 
     final Node node = attributes.item(i); 
     attributesString += node.getNodeName(); 
     attributesString += "="; 
     attributesString += "\"" + node.getNodeValue() + "\""; 
     if (i < attributes.getLength() - 1) { 
      attributesString += ","; 
     } 
    } 
    attributesString += "]"; 
    return attributesString; 
} 
+0

Спасибо Craig, он отлично работал для меня, но это не работает, если есть несколько родительских узлов, подобных этому примеру final String xmlString = " " \t +" " \t +" " \t + "" \t + "" \t + " " \t +" " \t +" " \t +" " \t +" " \t +" " \t + "" \t + ""; –