【发布时间】:2018-01-03 16:11:50
【问题描述】:
我正在将数据导出到 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();
}
}
}
【问题讨论】: