我想解析这种XML字符串:
<Objects>
<Object type="crs" obj_id="192">
<Title>Course 1</Title>
<Description>this is description</Description>
<CreateDate>2012-10-16 12:53:12</CreateDate>
<LastUpdate>2012-10-16 12:53:54</LastUpdate>
</Object>
<Object type="frm" obj_id="202">
<Title>Forum 1</Title>
<Description>this is description</Description>
<CreateDate>2012-10-30 01:06:41</CreateDate>
<LastUpdate>2012-10-30 01:06:41</LastUpdate>
</Object>
</Objects>
我使用相同的结构解析了XML字符串,但只使用了标签&lt;对象&gt;。现在我想获取标签Object中的信息以获得type =“xxx”的字符串。
这就是我做这些解析的方式:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource xml = new InputSource();
xml.setCharacterStream(xmlSTring);
Document doc = db.parse(xml);
NodeList nodes = doc.getElementsByTagName("Object");
// iterate objects
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
// get first attribute
NodeList ref_id = element.getElementsByTagName("title");
Element line = (Element) ref_id.item(0);
System.out.println("title: " + getCharacterDataFromElement(line));
}
}
catch (Exception e) {
e.printStackTrace();
}
private static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
提前致谢。
答案 0 :(得分:1)
答案 1 :(得分:0)
你也可以使用JAXB来解决这个问题。如果您有示例XML文件,则可以使用名为Trang的程序生成xsd。这是我使用该程序生成的xml文档的模式:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="Objects">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" ref="Object"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Object">
<xs:complexType>
<xs:sequence>
<xs:element ref="Title"/>
<xs:element ref="Description"/>
<xs:element ref="CreateDate"/>
<xs:element ref="LastUpdate"/>
</xs:sequence>
<xs:attribute name="obj_id" use="required" type="xs:integer"/>
<xs:attribute name="type" use="required" type="xs:NCName"/>
</xs:complexType>
</xs:element>
<xs:element name="Title" type="xs:string"/>
<xs:element name="Description" type="xs:string"/>
<xs:element name="CreateDate" type="xs:string"/>
<xs:element name="LastUpdate" type="xs:string"/>
</xs:schema>
然后,您可以使用JAXB为xml文档生成对象,并将xml绑定到这些对象。