java - 使用java获取XML文件中的所有标签

标签 java xml parsing dom sax

您好,我想获取 XML 中所有标签的列表,如果某些标签带有特定属性,我还需要该属性的值。 例如这里有一个具体的例子,

<?xml version="1.0" encoding="utf-8"?>
<bbc.mobile.news.view.AVGalleryView android:background="@drawable/gallery_item_selector" android:padding="2.0dip" android:focusable="true" android:layout_width="139.0dip" android:layout_height="130.0dip"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <bbc.mobile.news.view.NewsImageView android:id="@id/galleryItemView" android:background="#00000000" android:padding="0.0dip" android:layout_width="@dimen/thumbnail_width" android:layout_height="@dimen/thumbnail_height" />
    <TextView android:textSize="13.0sp" android:textColor="@color/thumbnail_text" android:ellipsize="end" android:id="@id/articleTitleId" android:background="@color/thumbnail_text_bg" android:paddingLeft="5.0dip" android:paddingTop="2.0dip" android:paddingBottom="5.0dip" android:layout_width="139.0dip" android:layout_height="50.0dip" android:maxLines="2" android:layout_below="@id/galleryItemView" />
    <ImageView android:layout_gravity="center_vertical" android:id="@id/avIconView" android:background="#99000000" android:duplicateParentState="true" android:layout_width="40.0dip" android:layout_height="40.0dip" android:src="@drawable/icon_playvideo_selected" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" />
</bbc.mobile.news.view.AVGalleryView>

我对父子关系不感兴趣,如果存在父子关系,我想迭代到最深的 child 。如果存在于特定元素中,我还想要 android:idandroid:name 属性值。

问题是您无法知道父子关系可以有多深以及它将在 xml 中的什么位置。而且您以前也不知道标签名称。我可以考虑在我的代码中使用递归,但我相信有一个更简单的解决方案

最佳答案

我找到了解决方案,非常简单,之前不知道 getElementsByTagName("*") 是这样做的,这是我的代码,

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    System.out.println("Root element " + doc.getDocumentElement().getNodeName());

    NodeList nodeList=doc.getElementsByTagName("*");
    for (int i=0; i<nodeList.getLength(); i++) 
    {
        // Get element
        Element element = (Element)nodeList.item(i);
        System.out.println(element.getNodeName());
    }

我找到了解决方案 here

关于java - 使用java获取XML文件中的所有标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12831530/

相关文章:

javascript - 使用类似 markdown 的标记语言递归解析字符串

java - Spring Boot 无法使用 ClassPathResource 找到文件

c# - 如何在现有的完全空的 .xml 文件中写入内容?

java - 用于验证内置 XSD 类型的正则表达式或库?

java - 在 Android Manifest.xml 中接收短信

c++ - 在 C++ 中解析 REST 查询

java - twilio 的 Whatsapp 群组

java - Android ListView 使用 baseAdapter 返回 null onItemClick

Java - 在 switch 语句中的 case 之间共享 int 值

arrays - Bash 解析动态数组并将特定值存储在另一个