2013-02-04 90 views
1

javax.xml.parsers.DocumentBuilder可以從XML文件的單個流構建文檔。但是,我找不到任何方式也給它一個模式文件。有沒有辦法爲XPath查詢提供Java文檔的XML模式

有沒有辦法做到這一點,使我的XPath查詢可以執行類型意識查詢並返回類型化數據?

+0

如果你想表示適當類型的元素和驗證文檔,請嘗試JAXB。您甚至可以在幾秒鐘內從XML Schema文檔生成類。 – toniedzwiedz

+0

你是什麼意思類型感知查詢和輸入數據?我只是表面上熟悉XPath,所以我不知道它們的含義。 –

+0

架構不應該與名稱空間相關聯並在源XML文檔中聲明嗎? –

回答

1

JAXP API專爲XPath 1.0設計,並且從未升級到處理2.0架構感知查詢等概念。如果您使用的是Saxon,請使用s9api接口而不是JAXP。

下面是s9apiExamples.java撒克遜資源下載採取的模式認識的XPath的例子:

/** 
* Demonstrate use of a schema-aware XPath expression 
*/ 

private static class XPathC implements S9APIExamples.Test { 
    public String name() { 
     return "XPathC"; 
    } 
    public boolean needsSaxonEE() { 
     return true; 
    } 
    public void run() throws SaxonApiException { 
    Processor proc = new Processor(true); 

    SchemaManager sm = proc.getSchemaManager(); 
    sm.load(new StreamSource(new File("data/books.xsd"))); 
    SchemaValidator sv = sm.newSchemaValidator(); 
    sv.setLax(false); 

    XPathCompiler xpath = proc.newXPathCompiler(); 
    xpath.declareNamespace("saxon", "http://saxon.sf.net/"); // not actually used, just for demonstration 
    xpath.importSchemaNamespace("");       // import schema for the non-namespace 

    DocumentBuilder builder = proc.newDocumentBuilder(); 
    builder.setLineNumbering(true); 
    builder.setWhitespaceStrippingPolicy(WhitespaceStrippingPolicy.ALL); 
    builder.setSchemaValidator(sv); 
    XdmNode booksDoc = builder.build(new File("data/books.xml")); 

    // find all the ITEM elements, and for each one display the TITLE child 

    XPathSelector verify = xpath.compile(". instance of document-node(schema-element(BOOKLIST))").load(); 
    verify.setContextItem(booksDoc); 
    if (((XdmAtomicValue)verify.evaluateSingle()).getBooleanValue()) { 
     XPathSelector selector = xpath.compile("//schema-element(ITEM)").load(); 
     selector.setContextItem(booksDoc); 
     QName titleName = new QName("TITLE"); 
     for (XdmItem item: selector) { 
      XdmNode title = getChild((XdmNode)item, titleName); 
      System.out.println(title.getNodeName() + 
        "(" + title.getLineNumber() + "): " + 
        title.getStringValue()); 
     } 
    } else { 
     System.out.println("Verification failed"); 
    } 
} 

// Helper method to get the first child of an element having a given name. 
// If there is no child with the given name it returns null 

private static XdmNode getChild(XdmNode parent, QName childName) { 
    XdmSequenceIterator iter = parent.axisIterator(Axis.CHILD, childName); 
    if (iter.hasNext()) { 
     return (XdmNode)iter.next(); 
    } else { 
     return null; 
    } 
}   

}

+0

XPath 1.0包含模式感知查詢。 dom4j/jaxen和.NET運行時一樣。我們目前使用dom4j/jaxen,它工作正常,但我想我們應該切換到標準的Java運行時,如果這已被添加。謝謝dave –

+0

不,XPath 1.0不包含模式感知 - 除非您使用的術語的含義與XPath 2.0規範使用它的方式完全不同。 –

+0

我使用的術語是dom4j/jaxen和Microsoft .NET庫使用它。從模式中,它們將節點轉換爲指定的類型,以用於比較和從XPath查詢返回類型化結果。 –

相關問題