使用Java从XML文件获取属性
我有一个具有以下结构的XML文件:使用Java从XML文件获取属性,java,xml,dom,extract,xml-parsing,Java,Xml,Dom,Extract,Xml Parsing,我有一个具有以下结构的XML文件: <?xml version="1.0"> <person> <element att1="value1" att2="value2">Anonymous</element> </person> 匿名的 如何使用您想要的方式提取属性名称和值 我尝试了JDOM,但仍然找不到从元素中获取属性的方法 Element root = doc.getRootElement(); List allChi
<?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()
}
Element root=doc.getRootElement();
List allChildren=root.getChildren();
迭代器i=listediants.Iterator();
while(i.hasNext())
{
元素当前=(元素)i.next();
System.out.println(current.getChild(“elementName”).getText();
//这样,我就可以使用JDOM(org.JDOM.Element)获得>anf中的值
只需使用:
current.getAttributes();
current.getAttributesValues();
current.getAttributeValue("AttributeName");
以下是文件:
编辑:下面是一个使用getAttributes()
List l_atts=current.getAttributes();
for(属性l_att:l_atts){
System.out.println(“Name=“+l_att.getName()+”| value=“+l_att.getValue());
}
编辑2:对于你的foo和moo问题,你只是不调用正确的元素上的getAttributes
。在调用它之前,你首先必须在name元素上,如果你使用简单的循环,而没有从你穿过的元素中得到子元素,你只会在“Student”上迭代元素。如果您确实知道属性的名称,则可以使用getAttributeValue
获取其值:
current.getAttributeValue("att1"); // value1
如果不知道属性的名称,则可以使用getAttributes()
并迭代每个属性
:
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
}
什么意思?你不知道属性的名称?getAttributes()可能就是您要查找的。因为它们是元素名称的属性,而不是学生,它由当前变量表示。为了获取名称节点,您需要获取学生
的子节点,即当前.getChildren()
,其中第一个将是name
。好的,我可以这样做,但是我如何知道元素有child?使用getchilds
,然后检查返回的列表的size()
。如果不知道属性名称,请使用getAttributes()然后遍历列表!如何从getAttributes()返回的列表中提取属性?使用迭代器或for循环,您可以遍历属性。Attribute
object然后提供许多方法来获取值或名称!getName()
和getValue()
例如
current.getAttributeValue("att1"); // value1
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
}