2011-08-03 40 views
2

我有一個XML文件,這種結構的XML文件的屬性:得到使用Java

<?xml version="1.0"> 
<person> 
    <element att1="value1" att2="value2">Anonymous</element> 
</person> 

如何使用您想wathever我提取屬性的名稱和值。

我試過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> 

回答

3

如果您知道屬性的名稱,那麼你可以使用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 
} 
+0

好的,現在假設你不知道元素裏面有什麼! –

+0

你是什麼意思?你不知道屬性的名字? –

+0

getAttributes()可能是你正在尋找的。 http://www.jdom.org/docs/apidocs/org/jdom/Element.html#getAttributes() – NeilMonday

2

使用JDOM(org.jdom.Element中) 只需使用:

current.getAttributes(); 
current.getAttributesValues(); 
current.getAttributeValue("AttributeName"); 

這裏是文檔: http://www.jdom.org/docs/apidocs/org/jdom/Element.html

編輯:下面是一個例子,你可以做什麼getAttributes()

List<Attribute> l_atts = current.getAttributes(); 
for (Attribute l_att : l_atts) { 
    System.out.println("Name = " + l_att.getName() + " | value = " + l_att.getValue()); 
} 

編輯2:爲了您的foo和moo問題,您只需在正確的Element上不要撥打getAttributes。在調用它之前,首先必須在名稱元素上,如果使用簡單的循環而不從您穿過的元素中獲取子元素,則只會遍歷「學生」元素。

+0

好的,現在假設你不知道元素內部是什麼! –

+0

如果您不知道屬性名稱,請使用getAttributes()並遍歷列表! – Dalshim

+0

如何從getAttributes()返回的列表中提取屬性? –