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

标签 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中的代码来获取标签元素的名称,例如: 标签属性的元素是(高度,宽度)

这是我的方法:

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/

相关文章:

amazon-web-services - 如何使用 AWS CLI 列出所有角色的标签

django - 遍历自定义模板标签传递的列表

java - 基本 Java 图形和坐标无法正常工作

java - 连接表并将结果保存在 ArrayList-Attribute 中

xml - 使用 Matlab 从 .XML 文件访问数据

java - 在 Tomcat7 服务器上用 Java 创建新实例时出现 XmlPullParser 异常

java - 将具有不同数据类型的文件读入树中

java - 用于保存 Excel 文件中的数据(然后用于生成可以编辑数据的 GUI)的最佳数据结构是什么?

javascript - 如何使用 jQuery 解析 XML?

php - 去掉不需要的标签后,我还应该对文本输入做什么?