使用java创建xml

时间:2015-07-02 07:07:25

标签: java xml

我想迭代下面给出的XML:

                <Annotation>
                    <Properties>
                        <PropertyValue PropertyName="field_label">label.modelSeriesCd</PropertyValue>
                        <PropertyValue PropertyName="ContainerType">conditionContainer</PropertyValue>
                    </Properties>
                </Annotation>

我正在尝试这些代码: 1)

while(currentNode.hasChildNodes()){
                        System.out.println(currentNode.getNextSibling());
                        currentNode=currentNode.getNextSibling();
                    }

2)

for (int x = 0; x < childNode.getLength(); x++) {
                    Node current = childNode.item(x);
                    if (Node.ELEMENT_NODE == current.getNodeType()) {
                        String cN = current.getNodeName();
                        System.out.print(cN +" = ");
                        String cV = current.getNodeValue();
                        System.out.print(cV+" : ");
                        String cT = current.getTextContent();
                        System.out.println(cT);
                    }
                }

输出:

[Shape: null]
ShapeType = null : H2
Annotation = null : 

                                label.modelSeriesCd
                                conditionContainer

我想要输出所有标签名称和标签值,即它应显示如下: 属性 适当的价值 PropertyName“field_label” value label.modelSeriesCd 意味着我希望输出所有标签,属性名称,属性值和文本值。 这样我就可以用另一种XML写它了

1 个答案:

答案 0 :(得分:1)

下面的方法在XML树上进行递归,打印请求的信息:

public static void printNodeTree(Node n) {
    // print XML Element name:
    System.out.println("ELEM: " + n.getNodeName());

    // print XML Element attributes:
    NamedNodeMap attrs = n.getAttributes();
    if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++ ) {
            Node attr = attrs.item(i);
            System.out.println("ATTR: " + attr.getNodeName() + " = " + attr.getNodeValue());
        }
    }

    NodeList nodeList = n.getChildNodes();

    // print XML Element text value
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.TEXT_NODE) {
            String text = currentNode.getNodeValue();
            if (text != null && text.matches("\\S+")) {
                System.out.println("TEXT: " + text);
            }
        }
    }

    // recurse over child elements 
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            printNodeTree(currentNode);
        }
    }
}

您可以从文档根目录启动遍历:

Document doc = ...
printNode(doc.getDocumentElement());

给定输入的输出:

ELEM: Annotation
ELEM: Properties
ELEM: PropertyValue
ATTR: PropertyName = field_label
TEXT: label.modelSeriesCd
ELEM: PropertyValue
ATTR: PropertyName = ContainerType
TEXT: conditionContainer