【发布时间】:2015-10-28 20:31:14
【问题描述】:
如果我有以下 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 中获取标签元素名称的代码,例如: 标签属性的元素是(Hight, Width)
这是我的方法:
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"] 的列表
【问题讨论】:
-
尝试发布您尝试过的内容。
-
您使用的是什么 xml 解析器?您当前的实施有什么问题?
-
@km1 我编辑了帖子
-
@azurefrog 我编辑了帖子
-
到目前为止是正确的。属性是一个节点,其他两个子节点......现在可以使用它......