2

私はここでいくつかの XML 解析を学習しようとしています。開始するためのコードがいくつか与えられています。私は使用しているさまざまな API についていくつかの調査を行い、コードを徐々にデバッグして、機能するものにすることができました。XPath クエリを文字列変数に配線して、XML ファイルを解析しようとしています。それがまったく役立つ場合は、 DocumentBuilderFactory も使用しています。とにかく、私はこの例外を受け取り続けます: Java.lang.String cannot be cast to 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 の一部です。XPath#evaluate(...)ただし、コア Java のメソッドでも通常は String が返されるため (1 つのオーバーロードを除く) 、結果は理にかなっています。

繰り返しますが、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

ゼロから始める場合は、Java ライブラリ標準クラス (org.w3c.dom.*) の代替として JDOM または DOM4J をお勧めします (両方のチュートリアルを参照)。彼らは扱いやすいです。Jaxen はその両方で動作します。

于 2014-11-25T04:44:33.027 に答える