java XML读取具有不同段的相同标记
下面是xml文件
<maindata>
<publication-reference>
<document-id document-id-type="docdb">
<country>US</country>
<doc-number>9820394ASD</doc-number>
<date>20111101</date>
</document-id>
<document-id document-id-type="docmain">
<doc-number>9820394</doc-number>
<date>20111101</date>
</document-id>
</publication-reference>
</maindata>
我想提取type=“docmain
”下的<doc-number>
标记值
下面是我的java代码,在执行其提取时9829394ASD
而不是9820394
public static void main(String[] args) {
String filePath ="D:/bs.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("publication-reference");
List<Biblio> docList = new ArrayList<Biblio>();
for (int i = 0; i < nodeList.getLength(); i++) {
docList.add(getdoc(nodeList.item(i)));
}
} catch (SAXException | ParserConfigurationException | IOException e1) {
e1.printStackTrace();
}
}
private static Biblio getdoc(Node node) {
Biblio bib = new Biblio();
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
bib.setCountry(getTagValue("country",element));
bib.setDocnumber(getTagValue("doc-number",element));
bib.setDate(getTagValue("date",element));
}
return bib;
}
让我知道我们如何检查其docmain或doctype的类型,仅当类型为docmain时才应提取,否则应离开元素
添加了getTagValue方法
private static String getTagValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
# 1 楼答案
谢谢你的帮助,下面是代码
# 2 楼答案
可以使用DOM and XPath API使用followingXPath检索该值
# 3 楼答案
更改方法
getdoc()
,使其仅为'docmain'类型创建Biblio
对象然后,在main方法中,如果
getdoc()
结果不为空,则只应将其添加到列表中:更新: 好吧,这太可怕了,抱歉。您应该真正了解一点XPath。 我试着用XPath表达式重写它
首先,我们需要四个XPath表达式。一个是提取一个节点列表,其中包含类型为
docmain
的所有document-id
元素其XPath表达式是:
/maindata/publication-reference/document-id[@document-id-type='docmain']
(上下文中的整个XML文档)这里[]中的谓词确保只提取类型为
docmain
的document-id
元素然后对于
document-id
元素中的每个字段(以document-id
元素作为上下文):country
doc-number
date
我们使用静态初始值设定项:
然后我们重写方法
getdoc
。该方法现在获取一个document-id
元素作为输入,并使用XPath表达式从中创建一个Biblio
实例:然后在
main()
方法中,使用XPath表达式仅提取所需的元素: