从java中的xml中获取标记中的元素

时间:2015-10-28 20:31:15

标签: java xml tags

如果我有以下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中的代码获取Example的标记元素的名称: 标签属性的元素是(高,宽)

这是我的方法:

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 =&#34;属性&#34;它返回包含[&#34;属性&#34;,&#34;属性&#34;,&#34;属性&#34;]

的列表

1 个答案:

答案 0 :(得分:-1)

找到<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);
    }
}