我将数据导出到xml文件中。我正在循环浏览导出各种数据的数据库,并且需要检查xml文档以查看它是否已经存在,因为我正在导出数据。
当我尝试使用xPath查询xml文档时,它返回null。我是否必须保存xml文件然后重新加载它以使xPath工作?难道我做错了什么?这是我下面的测试代码。注意,我尝试使用xmlDoc.selectNodes以及xPath。仍然没有爱
这是控制台输出
<?xml version="1.0" encoding="UTF-8"?>
<root>
<authors>
<author>
<name>Steven Rieger</name>
<location>Illinois</location>
</author>
<author>
<name>Dylan Rieger</name>
<location>Illinois</location>
</author>
</authors>
</root>
org.dom4j.tree.DefaultDocument@e26948 [Document: name null]
public class TestXML
{
public static void writeXmlDoc( Document document ) throws IOException
{
OutputFormat format = OutputFormat.createPrettyPrint();
// lets write to a file
XMLWriter writer = new XMLWriter( new FileWriter( "c:\\temp\\output.xml" ), format );
writer.write( document );
writer.close();
// Pretty print the document to System.out
writer = new XMLWriter( System.out, format );
writer.write( document );
}
public static void main( String[] args ) throws Exception
{
org.dom4j.Document xmlDoc;
List<Node> authors = null;
Element author = null;
try
{
xmlDoc = DocumentHelper.createDocument();
Element root = xmlDoc.addElement( "root" );
Element authorsElement = root.addElement( "authors" );
Element author1 = authorsElement.addElement( "author" );
author1.addElement( "name" ).addText( "Steven Rieger" );
author1.addElement( "location" ).addText( "Illinois" );
Element author2 = authorsElement.addElement( "author" );
author2.addElement( "name" ).addText( "Dylan Rieger" );
author2.addElement( "location" ).addText( "Illinois" );
writeXmlDoc( xmlDoc );
// authors = xmlDoc.selectNodes( "/authors" );
XPath xpathSelector = DocumentHelper.createXPath("/authors");
authors = xpathSelector.selectNodes( xmlDoc );
for (Iterator<Node> authorIterator = authors.iterator(); authorIterator.hasNext();)
{
author = (Element) authorIterator.next();
System.out.println( "Author: " + author.attributeValue( "name" ) );
System.out.println( " Location: " + author.attributeValue( "location" ) );
System.out.println( " FullName: " + author.getText() );
}
System.out.println( xmlDoc.toString() );
} catch ( Exception e )
{
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您的查询返回null,因为authors不是xml的根。您可以改用此xpath:
XPath xpathSelector = DocumentHelper.createXPath("/root/authors/author");
另一个问题是您首先将名称和状态存储为作者的子元素,但稍后您尝试将它们作为属性读取。 见https://www.w3schools.com/xml/xml_dtd_el_vs_attr.asp 您可以尝试在循环中阅读它们:
System.out.println("Author: " + author.selectSingleNode("name").getText());
System.out.println(" Location: " + author.selectSingleNode("location").getText());