java 获取 XML 元素中所有属性的列表或名称

发布于 2024-11-25 04:02:43 字数 618 浏览 0 评论 0原文

我有一个 xml 元素

   <base baseAtt1="aaa" baseAtt2="tt">
        <innerElement att1="one" att2="two" att3="bazinga"/>
   </base>

,我想获取属性列表。 对于基本元素和内部元素两者

不知道内部元素的名称 它可以有许多不同的名称。

 NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
 Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

目标是获得一种字典作为输出,

例如对于上面的 xml,输出将是具有这些值的字典。

baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"

我使用的是jre 1.5

i have an xml element

   <base baseAtt1="aaa" baseAtt2="tt">
        <innerElement att1="one" att2="two" att3="bazinga"/>
   </base>

and i would like to get the list of attributes.
for both the base element and the inner element.

i dont know the name of the innerElement
it can have many different names.

 NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
 Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

the goal is to get a kind of dictionary as output,

for example for the xml above the output will be a dictionary with those valuse.

baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"

i am using jre 1.5

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

腹黑女流氓 2024-12-02 04:02:43

这是基于 DOM 的普通解决方案(但是在 Java 中将 XPath 与 DOM 结合起来没有任何问题):

NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

NamedNodeMap baseElmnt_gold_attr = baseElmnt_gold.getAttributes();
for (int i = 0; i < baseElmnt_gold_attr.getLength(); ++i)
{
    Node attr = baseElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

NodeList innerElmntLst_gold = baseElmnt_gold.getChildNodes();
Element innerElement_gold = null;
for (int i = 0; i < innerElmntLst_gold.getLength(); ++i)
{
    if (innerElmntLst_gold.item(i) instanceof Element)
    {
        innerElement_gold = (Element) innerElmntLst_gold.item(i);
        break; // just get first child
    }
}

NamedNodeMap innerElmnt_gold_attr = innerElement_gold.getAttributes();
for (int i = 0; i < innerElmnt_gold_attr.getLength(); ++i)
{
    Node attr = innerElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

结果:

baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"

Here is plain DOM based solution (however there is nothing wrong to combine XPath with DOM in Java):

NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

NamedNodeMap baseElmnt_gold_attr = baseElmnt_gold.getAttributes();
for (int i = 0; i < baseElmnt_gold_attr.getLength(); ++i)
{
    Node attr = baseElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

NodeList innerElmntLst_gold = baseElmnt_gold.getChildNodes();
Element innerElement_gold = null;
for (int i = 0; i < innerElmntLst_gold.getLength(); ++i)
{
    if (innerElmntLst_gold.item(i) instanceof Element)
    {
        innerElement_gold = (Element) innerElmntLst_gold.item(i);
        break; // just get first child
    }
}

NamedNodeMap innerElmnt_gold_attr = innerElement_gold.getAttributes();
for (int i = 0; i < innerElmnt_gold_attr.getLength(); ++i)
{
    Node attr = innerElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

Result:

baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"
一个人的夜不怕黑 2024-12-02 04:02:43

您可以使用此 XPath 来检索第一个 element 节点的所有属性:

base/element[1]/@*

要获取 XML 中所有节点的所有属性,您可以使用以下表达式:

//@*

You can use this XPath to retrieve all attributes of 1st element node:

base/element[1]/@*

To get all attributes of all nodes in your XML yo can use this expression:

//@*
许久 2024-12-02 04:02:43

如果您使用 XPath,您的代码将会更少,但对于 dom 基础解决方案,我在这里有一个建议:

public void printElementsAndAttributes() throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    org.w3c.dom.Document doc = db.parse(new File("test.xml"));
    NodeList base = doc.getElementsByTagName("base");
    Node basenode = base.item(0);
    System.out.println(basenode.getNodeName() + getAttributesAsString(basenode.getAttributes()));
    NodeList children = basenode.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node item = children.item(i);
        if (item.getNodeType() == Node.ELEMENT_NODE) {
            System.out.println(item.getNodeName() + getAttributesAsString(item.getAttributes()));

        }
    }


}

private String getAttributesAsString(NamedNodeMap attributes) {
    StringBuilder sb = new StringBuilder("\n");
    for (int j = 0; j < attributes.getLength(); j++) {
        sb.append("\t- ").append(attributes.item(j).getNodeName()).append(": ").append(attributes.item(j).getNodeValue()).append("\n");
    }
    return sb.toString();

}

If you use XPath you will have less code, but for a dom base solution I have a suggestion here:

public void printElementsAndAttributes() throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    org.w3c.dom.Document doc = db.parse(new File("test.xml"));
    NodeList base = doc.getElementsByTagName("base");
    Node basenode = base.item(0);
    System.out.println(basenode.getNodeName() + getAttributesAsString(basenode.getAttributes()));
    NodeList children = basenode.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node item = children.item(i);
        if (item.getNodeType() == Node.ELEMENT_NODE) {
            System.out.println(item.getNodeName() + getAttributesAsString(item.getAttributes()));

        }
    }


}

private String getAttributesAsString(NamedNodeMap attributes) {
    StringBuilder sb = new StringBuilder("\n");
    for (int j = 0; j < attributes.getLength(); j++) {
        sb.append("\t- ").append(attributes.item(j).getNodeName()).append(": ").append(attributes.item(j).getNodeValue()).append("\n");
    }
    return sb.toString();

}
記柔刀 2024-12-02 04:02:43

使用此方法..

 public static void listAllAttributes(Element element) {

             System.out.println("List attributes for node: " + element.getNodeName());

             // get a map containing the attributes of this node
                 NamedNodeMap attributes = element.getAttributes();

             // get the number of nodes in this map

             int numAttrs = attributes.getLength();


             for (int i = 0; i < numAttrs; i++) {
            Attr attr = (Attr) attributes.item(i);
            String attrName = attr.getNodeName();

 String attrValue = attr.getNodeValue();
  System.out.println("Found attribute: " + attrName + " with value: " + attrValue);

             }
 }

通过在主方法中使用以下调用来调用此方法

  NodeList entries = doc.getElementsByTagName("NameOfTheNode");
                int num = entries.getLength();
                 for (int i=0; i<num; i++) {
                                                  Element node = (Element) entries.item(i);
                                                  listAllAttributes(node);

                          }

Use this method..

 public static void listAllAttributes(Element element) {

             System.out.println("List attributes for node: " + element.getNodeName());

             // get a map containing the attributes of this node
                 NamedNodeMap attributes = element.getAttributes();

             // get the number of nodes in this map

             int numAttrs = attributes.getLength();


             for (int i = 0; i < numAttrs; i++) {
            Attr attr = (Attr) attributes.item(i);
            String attrName = attr.getNodeName();

 String attrValue = attr.getNodeValue();
  System.out.println("Found attribute: " + attrName + " with value: " + attrValue);

             }
 }

call this method by using following call in the main method

  NodeList entries = doc.getElementsByTagName("NameOfTheNode");
                int num = entries.getLength();
                 for (int i=0; i<num; i++) {
                                                  Element node = (Element) entries.item(i);
                                                  listAllAttributes(node);

                          }
娇纵 2024-12-02 04:02:43
NodeList bList = eElement.getElementsByTagName("base");
Node node1 = bList.item(0);

if (node1.getNodeType() == node1.ELEMENT_NODE) {
                     Element ele = (Element) node1;
                     System.out.print("Attribute : ");
                     System.out.println(ele.getAttributes());
                  }

应该有效。

https://www.tutorialspoint.com/java_xml/java_xml_quick_guide.htm< 给出了非常好的解释/a> 为了更清楚,您可以参考它。

NodeList bList = eElement.getElementsByTagName("base");
Node node1 = bList.item(0);

if (node1.getNodeType() == node1.ELEMENT_NODE) {
                     Element ele = (Element) node1;
                     System.out.print("Attribute : ");
                     System.out.println(ele.getAttributes());
                  }

Should work.

Very nice explanation is given at https://www.tutorialspoint.com/java_xml/java_xml_quick_guide.htm You can refer that for more clarity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文