请告诉我在java中解析下面的xml的最佳方法。这里我对root(元素)和其他节点有相同的名称。是否可以使用jaxb或者我必须坚持使用正常的dom?
<element exp="office_adr" display="false" id="o_a2">
<element exp="office1" display="false" id="o2">
<element exp="city1" display="false" id="c1">
<element exp="address1" display="true" id="h_1">
<element exp="ad1" display="false" id="h_2"/>
<element exp="ad2" display="false" id="h_3"/>
<element exp="ad3" display="false" id="h_4"/>
<element exp="ad4" display="false" id="h_5"/>
<element exp="ad5" display="false" id="h_6"/>
</element>
<element exp="address2" display="true" id="h_8">
<element exp="ad7" display="false" id="h_9"/>
<element exp="ad8" display="false" id="h_10"/>
</element>
<element exp="address3" display="true" id="h_11">
<element exp="ad9" display="false" id="h_12"/>
</element>
</element>
</element>
<element exp="office2" display="false" id="o2">
<element exp="city2" display="false" id="c2">
<element exp="address3" display="true" id="a_1">
<element exp="ad1" display="false" id="a_2"/>
<element exp="ad2" display="false" id="a_3"/>
<element exp="ad3" display="false" id="a_4"/>
<element exp="ad4" display="false" id="a_5"/>
<element exp="ad5" display="false" id="a_6"/>
</element>
<element exp="address2" display="true" id="a_8">
<element exp="ad7" display="false" id="a_9"/>
<element exp="ad8" display="false" id="a_10"/>
</element>
<element exp="address3" display="true" id="a_11">
<element exp="ad9" display="false" id="a_12"/>
</element>
</element>
</element>
</element>
答案 0 :(得分:2)
JAXB没问题:
package test;
import java.io.File;
import java.util.Collection;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAttribute;
public class Element
{
private String exp;
private boolean display;
private String id;
private Collection<Element> element;
@XmlAttribute
public String getExp()
{
return exp;
}
public void setExp(String exp)
{
this.exp = exp;
}
@XmlAttribute
public boolean isDisplay()
{
return display;
}
public void setDisplay(boolean display)
{
this.display = display;
}
@XmlAttribute
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public Collection<Element> getElement()
{
return element;
}
public void setElement(Collection<Element> element)
{
this.element = element;
}
public static void main(String[] args)
{
Element e = JAXB.unmarshal(new File("C:/testFile.xml"), Element.class);
System.out.println(e.getElement().size());
}
}
答案 1 :(得分:0)
对于SAX,DOM或任何其他XML处理代码没有问题。这是编写XML的一种特别难看的方式,但它完全合法。