gpt4 book ai didi

java - java中从xml中的标签获取元素

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

如果我有以下 xml:

<Shapes>
<Numbers>n-3</Numbers>
<Ellipse.0>
<Color>
<Red>r-0</Red>
<Green>g-0</Green>
<Blue>b-255</Blue>
</Color>
<FillColor>
<Red>r-0</Red>
<Green>g-0</Green>
<Blue>b-255</Blue>
</FillColor>
<Position>
<X>x-12</X>
<Y>y-12</Y>
</Position>
<properties>
<Hight>v-123.0</Hight>
<Width>v-12.0</Width>
</properties>
</Ellipse.0>
</Shapes>

我想要java中的代码来获取标签元素的名称,例如:标签属性的元素是(高度,宽度)

这是我的方法:

public static List<String> getNodes(String fileName, String nodeName) throws ParserConfigurationException, SAXException, IOException{   

try {
List<String> nodes = new ArrayList<String>();
// Create a factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Use the factory to create a builder
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(fileName);

NodeList list = doc.getElementsByTagName(nodeName);

for (int i = 0; i < list.getLength(); i++) {
// Get element
Element element = (Element) list.item(i);
nodes.add(element.getNodeName());

}
return nodes;
} catch (Exception e) {
throw new RuntimeException();
}
}

如果nodeName =“Properties”,则返回包含[“Properties”,“Properties”,“Properties”]的列表

最佳答案

找到 <properties> 后您想要提取其子节点名称的节点。这对我有用:

List<String> nodes = new ArrayList<String>();
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(fileName);
NodeList list = doc.getElementsByTagName(nodeName); // find <properties> node(s)
NodeList childList = list.item(0).getChildNodes(); // list.item(0) is first (and only) match
for (int i = 0; i < childList.getLength(); i++) {
Node childNode = childList.item(i);
String childNodeName = childNode.getNodeName();
if (!childNodeName.equals("#text")) {
nodes.add(childNodeName);
}
}

关于java - java中从xml中的标签获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33401046/

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