2

我正在尝试在这里学习一些 XML 解析,并且我已经获得了一些代码来开始。我已经对我正在使用的不同 API 进行了一些研究,并且我逐渐能够将我的代码调试成我希望能够工作的东西。我试图通过将 XPath 查询硬连接到字符串变量来解析 XML 文件。如果有帮助的话,我也在使用 DocumentBuilderFactory。无论如何,我不断收到此异常:Java.lang.String 无法转换为 org.w3c.dom.Node(我已在下面的代码中对其进行了标记)。我明白错误是什么。字符串查询似乎与“评估”方法的参数不一致。只是不知道如何解决它。我尝试了各种不同的演员阵容,但它们都不起作用。有些东西告诉我我在这里做错了什么......请帮忙!PS。对不起,我的代码有点乱,我对解析完全陌生,我也知道有一些不必要的导入,但我想如果我进行一些更改,我可能需要它们。

代码:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;

import org.jaxen.JaxenException;
import org.jaxen.dom.DOMXPath;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class Parser 
{
public static void main(String[] args) 
{
    boolean isNamespaceAware = true;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(isNamespaceAware);
    DocumentBuilder builder = null;
    try 
    {
        builder = dbf.newDocumentBuilder();
    } 
    catch (ParserConfigurationException e2)
    {
        e2.printStackTrace();
    } 
    try 
    {
        Document workingDocument =
builder.parse("C:\\Users\\Brandon\\Job\\XPath\\XPath_Sample_Stuff\\XPath_Objects.xml");
    } 
    catch (SAXException e1) 
    {
        e1.printStackTrace();
    } 
    catch (IOException e1) 
    {
        e1.printStackTrace();
    } 
    String xPathQuery = "/book/author"; 
    DOMXPath generatedPath;
    String results = null;
    try 
    {
        generatedPath = new DOMXPath(xPathQuery);
//Here is the errror
        results = generatedPath.evaluate(xPathQuery); 
    } 
    catch (JaxenException e) 
    {
        e.printStackTrace();
    }   
    if(results == null)
        System.err.println("There was an issue processing the xpath, and
 results were still null.");
    for (int i=0; i<= results.getLength();i++)
    {
        System.out.println(results.item(i));
    }
}                   

}

这是我收到的 XML 文件中的一些 XML:

 <?xml version="1.0"?>
 <catalog> 
 <book id="bk101"> 
  <author>Gambardella, Matthew</author> 
  <title>XML Developer's Guide</title> 
  <genre>Computer</genre>
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date> 
  <description>An in-depth look at creating applications with XML.</description> 
</book> 
4

2 回答 2

1

该错误告诉您该DOMXPath#evaluate(...)方法返回一个字符串。您正在尝试将其转换为 NodeList,但事实并非如此。此方法的 API 将解释所有内容——但同样,该 API 不是标准 Java 的一部分,而是 Jaxen 的一部分。但是即使对于核心 Java,结果也是有意义的,因为它的XPath#evaluate(...)方法通常也返回一个字符串(除了一个重载)。

同样,也许您现在不想使用 Jaxen,除非您有充分的理由这样做但还没有告诉我们。

编辑
假设您在文件 Catalog.xml 中有一个 XML,如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<catalog>
    <book id="bk101">
        <author>Smith, John</author>
        <title>Fubars Rule</title>
        <price>100.1</price>
        <date>2012-10-01</date>
        <description>A witty exposé</description>
    </book>
    <book id="bk102">
        <author>Python, Monty</author>
        <title>Your Hovercraft is full of Eels</title>
        <price>250.5</price>
        <date>10-01-01</date>
        <description>an even wittier exposé</description>
    </book>
</catalog>

JAXB 可以在您的常规课程中仅使用一些注释来编组/解组该傻瓜。这使得这样做几乎是白痴证明。例如:

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

public class CatalogTest {
   private static final String PATH_NAME = "Catalog.xml";



   public static void main(String[] args) {
      // comment one of the lines below and un-comment the other to test
      // marshallTest(); 
      unmarshallTest();
   }



   private static void unmarshallTest() {
      JAXBContext context;
      try {
         context = JAXBContext.newInstance(Catalog.class);
         Unmarshaller unmarshaller = context.createUnmarshaller();
         File catalogFile  = new File(PATH_NAME);
         Catalog catalog = (Catalog) unmarshaller.unmarshal(catalogFile  );
         System.out.println(catalog);
      } catch (JAXBException e) {
         e.printStackTrace();
      }

   }



   private static void marshallTest() {
      try {
         Book[] books = {
               new Book("bk101", "Smith, John", "Fubars Rule", 100.10, "2012-10-01", "A witty exposé"),
               new Book("bk102", "Python, Monty", "Your Hovercraft is full of Eels", 250.50, "10-01-01", "an even wittier exposé")
         };
         Catalog catalog = new Catalog();
         for (Book book : books) {
            catalog.addBook(book);
         }
         JAXBContext context = JAXBContext.newInstance(Catalog.class);
         Marshaller marshaller = context.createMarshaller();
         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

         File catalogFile = new File(PATH_NAME);
         marshaller.marshal(catalog, catalogFile);

      } catch (JAXBException e) {
         e.printStackTrace();
      }
   }
}

@XmlRootElement
class Catalog {
   @XmlElement(name = "book")
   private List<Book> bookList = new ArrayList<Book>();

   public List<Book> getBookList() {
      return bookList;
   }

   public void addBook(Book book) {
      bookList.add(book);
   }

   @Override
   public String toString() {
      return "Catalog [bookList=" + bookList + "]";
   }


}

@XmlRootElement
@XmlType(propOrder = { "author", "title", "price", "date", "description"})
class Book {
   private String id;
   private String author;
   private String title;
   private double price;
   private String date;
   private String description;

   public Book() {
   }

   public Book(String id, String author, String title, double price,
         String date, String description) {
      this.id = id;
      this.author = author;
      this.title = title;
      this.price = price;
      this.date = date;
      this.description = description;
   }

   @XmlAttribute(name = "id")
   public String getId() {
      return id;
   }

   public void setId(String id) {
      this.id = id;
   }

   public String getAuthor() {
      return author;
   }

   public void setAuthor(String author) {
      this.author = author;
   }

   public String getTitle() {
      return title;
   }

   public void setTitle(String title) {
      this.title = title;
   }

   public double getPrice() {
      return price;
   }

   public void setPrice(double price) {
      this.price = price;
   }

   public String getDate() {
      return date;
   }

   public void setDate(String date) {
      this.date = date;
   }

   public String getDescription() {
      return description;
   }

   public void setDescription(String description) {
      this.description = description;
   }

   @Override
   public String toString() {
      return "Book [id=" + id + ", author=" + author + ", title=" + title
            + ", price=" + price + ", date=" + date + ", description="
            + description + "]";
   }

}
于 2012-07-01T04:23:12.430 回答
0

如果从头开始,我会建议将 JDOM 或 DOM4J 作为 Java 库标准类 (org.w3c.dom.*) 的替代品(查看两者的教程)。他们更容易使用。Jaxen 将与他们两人合作。

于 2014-11-25T04:44:33.027 回答