我有一个具有以下结构的 XML 文件:
<?xml version="1.0">
<person>
<element att1="value1" att2="value2">Anonymous</element>
</person>
如何使用您想要的任何方式提取属性名称和值。
我尝试了 JDOM,但仍然找不到从元素获取属性的方法。
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。
<?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
获取其值:
current.getAttributeValue("att1"); // value1
如果您不知道属性的名称,则可以使用 getAttributes()
并迭代每个 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 - 使用 Java 从 XML 文件获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6927385/