java 获取 XML 元素中所有属性的列表或名称
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是基于 DOM 的普通解决方案(但是在 Java 中将 XPath 与 DOM 结合起来没有任何问题):
结果:
Here is plain DOM based solution (however there is nothing wrong to combine XPath with DOM in Java):
Result:
您可以使用此 XPath 来检索第一个
element
节点的所有属性:要获取 XML 中所有节点的所有属性,您可以使用以下表达式:
You can use this XPath to retrieve all attributes of 1st
element
node:To get all attributes of all nodes in your XML yo can use this expression:
如果您使用 XPath,您的代码将会更少,但对于 dom 基础解决方案,我在这里有一个建议:
If you use XPath you will have less code, but for a dom base solution I have a suggestion here:
使用此方法..
通过在主方法中使用以下调用来调用此方法
Use this method..
call this method by using following call in the main method
应该有效。
https://www.tutorialspoint.com/java_xml/java_xml_quick_guide.htm< 给出了非常好的解释/a> 为了更清楚,您可以参考它。
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.