【问题标题】:Get elements from tags in xml in java从java中的xml中的标签获取元素
【发布时间】: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 我编辑了帖子
  • 到目前为止是正确的。属性是一个节点,其他两个子节点......现在可以使用它......

标签: java xml tags


【解决方案1】:

找到&lt;properties&gt; 节点后,您希望提取其子节点的名称。这对我有用:

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

【讨论】:

  • 它是如何工作的? OP 从中学到了什么?为什么他会花时间解决下一个问题,而不是简单地回到这里让别人再次为他们工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
  • 2021-07-01
  • 2013-10-12
  • 2011-09-16
  • 2018-08-06
相关资源
最近更新 更多