gpt4 book ai didi

java - 使用java创建xml

转载 作者:行者123 更新时间:2023-11-30 11:01:29 26 4
gpt4 key购买 nike

我想遍历下面给出的 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

我想要包含所有标签名称和标签值的输出,即它应该显示如下:特性适当的值(value)属性名称“field_label”值标签.modelSeriesCd意味着我想要输出所有标签、属性名称、属性值和文本值。这样我就可以用另一个 XML 编写它

最佳答案

下面的方法在 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

关于java - 使用java创建xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31177733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com