使用Java从XML文件获取属性 [英] get the attributes from an XML File using Java
本文介绍了使用Java从XML文件获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有以下结构的XML文件:
I have an XML file with this structure:
<?xml version="1.0">
<person>
<element att1="value1" att2="value2">Anonymous</element>
</person>
如何使用所需的路径提取属性名称和值。
How can I extract the attributes names and values using wathever you want.
我尝试了JDOM,但仍然找不到从元素中获取属性的方法。
I tried JDOM, but I still can't find a way to get the attributes from the element.
Element root = doc.getRootElement();
List allChildren = root.getChildren();
Iterator i = listEtudiants.iterator();
while(i.hasNext())
{
Element current = (Element)i.next();
System.out.println(current.getChild("elementName").getText());
// this let me get just the value inside > anf </
// so, if it's can be done by completing this code
// it will be something like current.getSomething()
}
编辑:我仍然对该文件有问题。我无法获得foo属性及其值moo。
I'm still having a problem with this file. I can't reach foo attribute and its value moo.
<?xml version="1.0" encoding="UTF-8"?>
<person>
<student att1="v1" att2="v2">
<name>Michel</name>
<prenames>
<prename>smith</prename>
<prename>jack</prename>
</prenames>
</student>
<student classe="P1">
<name foo="moo">superstar</name>
</student>
</person>
推荐答案
如果您确实知道属性的名称,则您可以使用 getAttributeValue
来获取其值:
If you do know the name of the attribute, then you can use getAttributeValue
to obtain its value:
current.getAttributeValue("att1"); // value1
如果您不知道属性名称,则可以使用 getAttributes()
并遍历每个 Attribute
:
If you do not know the name of the attribute(s), then you can use getAttributes()
and iterate over each Attribute
:
List attributes = current.getAttributes();
Iterator it = attributes.iterator();
while (it.hasNext()) {
Attribute att = (Attribute)it.next();
System.out.println(att.getName()); // att1
System.out.println(att.getValue()); // value1
}
这篇关于使用Java从XML文件获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文