如果想要在 xpath 表達式中使用名稱空間,必須提供對此名稱空間 uri 所用前綴的鏈接。本文介紹了向名稱空間映射提供前綴的三種不同方式。本文亦包含了示例代碼以方便您編寫自己的 namespacecontext。
前提條件和示例
本文所有的示例均使用如下這個xml文件:
清單1. 示例xml
<?xml version="1.0" encoding="utf-8"?><books:booklist xmlns:books="http://univnaspresolver/booklist" xmlns="http://univnaspresolver/book" xmlns:fiction="http://univnaspresolver/fictionbook"> <science:book xmlns:science="http://univnaspresolver/sciencebook"> <title>learning xpath</title> <author>michael schmidt</author> </science:book> <fiction:book> <title>faust i</title> <author>johann wolfgang von goethe</author> </fiction:book> <fiction:book> <title>faust ii</title> <author>johann wolfgang von goethe</author> </fiction:book></books:booklist> |
這個 xml 示例包含三個在根元素內聲明的名稱空間,一個在此結構的更深層元素上聲明的名稱空間。您將可以看到這種設置所帶來的差異。
這個 xml 示例的第二個有趣之處在于元素 booklist 具有三個子元素,均名為 book。但是第一個子元素具有名稱空間 science,而其他子元素則具有名稱空間 fiction。這意味著這些元素完全有別于 xpath。在接下來的這些例子中,您將可以看到這種特性產生的結果。
示例源代碼中有一個需要注意之處:此代碼沒有針對維護進行優化,只針對可讀性進行了優化。這意味著它將具有某些冗余。輸出通過 system.out.println() 以最為簡單的方式生成。在本文中有關輸出的代碼行均縮寫為 “...”。
理論背景
名稱空間究竟有何意義?為何要如此關注它呢?名稱空間是元素或屬性的標識符的一部分。元素或屬性可以具有相同的本地名稱,但是必須使用不同的名稱空間。它們完全不同。請參考上述示例(science:book 和 fiction:book)。若要綜合來自不同資源的 xml 文件,就需要使用名稱空間來解決命名沖突。以一個 xslt 文件為例。它包含 xslt 名稱空間的元素、來自您自己名稱空間的元素以及(通常)xhtml 名稱空間的元素。使用名稱空間,就可以避免具有相同本地名稱的元素所帶來的不確定性。
名稱空間由 uri(在本例中為 http://univnaspresolver/booklist)定義。為了避免使用這個長字符串,可以定義一個與此 uri 相關聯的前綴(在本例中為 books)。請記住此前綴類似于一個變量:其名稱并不重要。如果兩個前綴引用相同的 uri,那么被加上前綴的元素的名稱空間將是相同的(請參見 清單 5 中的示例 1)。
xpath 表達式使用前綴(比如 books:booklist/science:book)并且您必須提供與每個前綴相關聯的 uri。這時,就需要使用 namespacecontext。它恰好能夠實現此目的。
本文給出了提供前綴和 uri 之間的映射的不同方式。
在此 xml 文件中,映射由類似 xmlns:books="http://univnaspresolver/booklist" 這樣的 xmlns 屬性或 xmlns="http://univnaspresolver/book"(默認名稱空間)提供。
|||
|||
|||
從文檔讀取名稱空間并緩存它們
namespacecontext 的下一個版本要稍好一些。它只在構造函數內提前讀取一次名稱空間。對一個名稱空間的每次調用均回應自緩存。這樣一來,文檔內的更改就變得無關緊要,因為名稱空間列表在 java 對象創建之時就已被緩存。
清單 10. 從文檔緩存名稱空間解析
public class universalnamespacecache implements namespacecontext { private static final string default_ns = "default"; private map<string, string> prefix2uri = new hashmap<string, string>(); private map<string, string> uri2prefix = new hashmap<string, string>(); /** * this constructor parses the document and stores all namespaces it can * find. if toplevelonly is true, only namespaces in the root are used. * * @param document * source document * @param toplevelonly * restriction of the search to enhance performance */ public universalnamespacecache(document document, boolean toplevelonly) { examinenode(document.getfirstchild(), toplevelonly); system.out.println("the list of the cached namespaces:"); for (string key : prefix2uri.keyset()) { system.out .println("prefix " + key + ": uri " + prefix2uri.get(key)); } } /** * a single node is read, the namespace attributes are extracted and stored. * * @param node * to examine * @param attributesonly, * if true no recursion happens */ private void examinenode(node node, boolean attributesonly) { namednodemap attributes = node.getattributes(); for (int i = 0; i < attributes.getlength(); i++) { node attribute = attributes.item(i); storeattribute((attr) attribute); } if (!attributesonly) { nodelist chields = node.getchildnodes(); for (int i = 0; i < chields.getlength(); i++) { node chield = chields.item(i); if (chield.getnodetype() == node.element_node) examinenode(chield, false); } } } /** * this method looks at an attribute and stores it, if it is a namespace * attribute. * * @param attribute * to examine */ private void storeattribute(attr attribute) { // examine the attributes in namespace xmlns if (attribute.getnamespaceuri() != null && attribute.getnamespaceuri().equals( xmlconstants.xmlns_attribute_ns_uri)) { // default namespace xmlns="uri goes here" if (attribute.getnodename().equals(xmlconstants.xmlns_attribute)) { putincache(default_ns, attribute.getnodevalue()); } else { // the defined prefixes are stored here putincache(attribute.getlocalname(), attribute.getnodevalue()); } } } private void putincache(string prefix, string uri) { prefix2uri.put(prefix, uri); uri2prefix.put(uri, prefix); } /** * this method is called by xpath. it returns the default namespace, if the * prefix is null or "". * * @param prefix * to search for * @return uri */ public string getnamespaceuri(string prefix) { if (prefix == null || prefix.equals(xmlconstants.default_ns_prefix)) { return prefix2uri.get(default_ns); } else { return prefix2uri.get(prefix); } } /** * this method is not needed in this context, but can be implemented in a * similar way. */ public string getprefix(string namespaceuri) { return uri2prefix.get(namespaceuri); } public iterator getprefixes(string namespaceuri) { // not implemented return null; }} |
請注意在代碼中有一個調試輸出。每個節點的屬性均被檢查和存儲。但子節點不被檢查,因為構造函數內的布爾值 toplevelonly 被設置為 true。如果此布爾值被設為 false,那么子節點的檢查將會在屬性存儲完畢后開始。有關此代碼,有一點需要注意:在 dom 中,第一個節點代表整個文檔,所以,要讓元素 book 讀取這些名稱空間,必須訪問子節點剛好一次。
在這種情況下,使用 namespacecontext 非常簡單:
清單 11. 具有緩存了的名稱空間解析的示例 3(只面向頂級)
private static void example3(document example) throws xpathexpressionexception, transformerexception { sysout("/n*** third example - namespaces of toplevel node cached ***"); xpath xpath = xpathfactory.newinstance().newxpath(); xpath.setnamespacecontext(new universalnamespacecache(example, true)); try {... nodelist result1 = (nodelist) xpath.evaluate( "books:booklist/science:book", example, xpathconstants.nodeset);... } catch (xpathexpressionexception e) {... }... nodelist result2 = (nodelist) xpath.evaluate( "books:booklist/fiction:book", example, xpathconstants.nodeset);... string result = xpath.evaluate( "books:booklist/fiction:book[1]/:author", example);... } |
這會導致如下輸出:
清單 12. 示例 3 的輸出
*** third example - namespaces of toplevel node cached ***the list of the cached namespaces:prefix default: uri http://univnaspresolver/bookprefix fiction: uri http://univnaspresolver/fictionbookprefix books: uri http://univnaspresolver/booklisttry to use the science prefix:--> books:booklist/science:bookthe cache only knows namespaces of the first level!the fiction namespace is such a namespace:--> books:booklist/fiction:booknumber of nodes: 2<?xml version="1.0" encoding="utf-8"?> <fiction:book xmlns:fiction="http://univnaspresolver/fictionbook"> <title xmlns="http://univnaspresolver/book">faust i</title> <author xmlns="http://univnaspresolver/book">johann wolfgang von goethe</author> </fiction:book><?xml version="1.0" encoding="utf-8"?> <fiction:book xmlns:fiction="http://univnaspresolver/fictionbook"> <title xmlns="http://univnaspresolver/book">faust ii</title> <author xmlns="http://univnaspresolver/book">johann wolfgang von goethe</author> </fiction:book>the default namespace works also:--> books:booklist/fiction:book[1]/:authorjohann wolfgang von goethe |
上述代碼只找到了根元素的名稱空間。更準確的說法是:此節點的名稱空間被構造函數傳遞給了方法 examinenode。這會加速構造函數的運行,因它無需迭代整個文檔。不過,正如您從輸出看到的,science 前綴不能被解析。xpath 表達式導致了一個異常(xpathexpressionexception)。
|||
從文檔及其所有元素讀取名稱空間并對之進行緩存
此版本將從這個 xml 文件讀取所有名稱空間聲明。現在,即便是前綴 science 上的 xpath 也是有效的。但是有一種情況讓此版本有些復雜:如果一個前綴重載(在不同 uri 上的嵌套元素內聲明),所找到的最后一個將會 “勝出”。在實際中,這通常不成問題。
在本例中,namespacecontext 的使用與前一個示例相同。構造函數內的布爾值 toplevelonly 必須被設置為 false。
清單 13. 具有緩存了的名稱空間解析的示例 4(面向所有級別)
private static void example4(document example) throws xpathexpressionexception, transformerexception { sysout("/n*** fourth example - namespaces all levels cached ***"); xpath xpath = xpathfactory.newinstance().newxpath(); xpath.setnamespacecontext(new universalnamespacecache(example, false));... nodelist result1 = (nodelist) xpath.evaluate( "books:booklist/science:book", example, xpathconstants.nodeset);... nodelist result2 = (nodelist) xpath.evaluate( "books:booklist/fiction:book", example, xpathconstants.nodeset);... string result = xpath.evaluate( "books:booklist/fiction:book[1]/:author", example);... } |
其輸出結果如下:
清單 14. 示例 4 的輸出
*** fourth example - namespaces all levels cached ***the list of the cached namespaces:prefix science: uri http://univnaspresolver/sciencebookprefix default: uri http://univnaspresolver/bookprefix fiction: uri http://univnaspresolver/fictionbookprefix books: uri http://univnaspresolver/booklistnow the use of the science prefix works as well:--> books:booklist/science:booknumber of nodes: 1<?xml version="1.0" encoding="utf-8"?> <science:book xmlns:science="http://univnaspresolver/sciencebook"> <title xmlns="http://univnaspresolver/book">learning xpath</title> <author xmlns="http://univnaspresolver/book">michael schmidt</author> </science:book>the fiction namespace is resolved:--> books:booklist/fiction:booknumber of nodes: 2<?xml version="1.0" encoding="utf-8"?> <fiction:book xmlns:fiction="http://univnaspresolver/fictionbook"> <title xmlns="http://univnaspresolver/book">faust i</title> <author xmlns="http://univnaspresolver/book">johann wolfgang von goethe</author> </fiction:book><?xml version="1.0" encoding="utf-8"?> <fiction:book xmlns:fiction="http://univnaspresolver/fictionbook"> <title xmlns="http://univnaspresolver/book">faust ii</title> <author xmlns="http://univnaspresolver/book">johann wolfgang von goethe</author> </fiction:book>the default namespace works also:--> books:booklist/fiction:book[1]/:authorjohann wolfgang von goethe |
結束語
實現名稱空間解析,有幾種方式可供選擇,這些方式大都好于硬編碼的實現方式:
•如果示例很小并且所有名稱空間均位于頂部元素內,指派到此文檔的方式將會十分有效。
•如果 xml 文件較大且具有深層嵌套和多個 xpath 求值,最好是緩存名稱空間的列表。
•但是如果您無法控制 xml 文件,并且別人可以發送給您任何前綴,最好是獨立于他人的選擇。您可以編碼實現您自己的名稱空間解析,如示例 1 (hardcodednamespaceresolver)所示,并將它們用于您的 xpath 表達式。
在上述這些情況下,解析自此 xml 文件的 namespacecontext 能夠讓您的代碼更少、并且更為通用。
從文檔讀取名稱空間
名稱空間及其前綴均存檔在此 xml 文件內,因此可以從那里使用它們。實現此目的的最為簡單的方式是將這個查找指派給該文檔。
清單 7. 從文檔直接進行名稱空間解析
public class universalnamespaceresolver implements namespacecontext { // the delegate private document sourcedocument; /** * this constructor stores the source document to search the namespaces in * it. * * @param document * source document */ public universalnamespaceresolver(document document) { sourcedocument = document; } /** * the lookup for the namespace uris is delegated to the stored document. * * @param prefix * to search for * @return uri */ public string getnamespaceuri(string prefix) { if (prefix.equals(xmlconstants.default_ns_prefix)) { return sourcedocument.lookupnamespaceuri(null); } else { return sourcedocument.lookupnamespaceuri(prefix); } } /** * this method is not needed in this context, but can be implemented in a * similar way. */ public string getprefix(string namespaceuri) { return sourcedocument.lookupprefix(namespaceuri); } public iterator getprefixes(string namespaceuri) { // not implemented yet return null; }} |
請注意如下這些事項:
•如果文檔在使用 xpath 前已更改,那么此更改還將反應在名稱空間的這個查找上,因為指派是在需要的時候通過使用文檔的當前版本完成的。
•對名稱空間或前綴的查找在所用節點的祖先節點完成,在我們的例子中,即節點 sourcedocument。這意味著,借助所提供的代碼,您只需在根節點上聲明此名稱空間。在我們的示例中,名稱空間 science 沒有被找到。
•此查找在 xpath 求值時被調用,因此它會消耗一些額外的時間。
如下是示例代碼:
清單 8. 從文檔直接進行名稱空間解析的示例 2
private static void example2(document example) throws xpathexpressionexception, transformerexception { sysout("/n*** second example - namespacelookup delegated to document ***"); xpath xpath = xpathfactory.newinstance().newxpath(); xpath.setnamespacecontext(new universalnamespaceresolver(example)); try {... nodelist result1 = (nodelist) xpath.evaluate( "books:booklist/science:book", example, xpathconstants.nodeset);... } catch (xpathexpressionexception e) {... }... nodelist result2 = (nodelist) xpath.evaluate( "books:booklist/fiction:book", example, xpathconstants.nodeset);... string result = xpath.evaluate( "books:booklist/fiction:book[1]/:author", example);... } |
此示例的輸出為:
清單 9. 示例 2 的輸出
*** second example - namespacelookup delegated to document ***try to use the science prefix: no result--> books:booklist/science:bookthe resolver only knows namespaces of the first level!to be precise: only namespaces above the node, passed in the constructor.the fiction namespace is such a namespace:--> books:booklist/fiction:booknumber of nodes: 2<?xml version="1.0" encoding="utf-8"?> <fiction:book xmlns:fiction="http://univnaspresolver/fictionbook"> <title xmlns="http://univnaspresolver/book">faust i</title> <author xmlns="http://univnaspresolver/book">johann wolfgang von goethe</author> </fiction:book><?xml version="1.0" encoding="utf-8"?> <fiction:book xmlns:fiction="http://univnaspresolver/fictionbook"> <title xmlns="http://univnaspresolver/book">faust ii</title> <author xmlns="http://univnaspresolver/book">johann wolfgang von goethe</author> </fiction:book>the default namespace works also:--> books:booklist/fiction:book[1]/:authorjohann wolfgang von goethe |
正如輸出所示,在 book 元素上聲明的、具有前綴 science 的名稱空間并未被解析。求值方法拋出了一個 xpathexpressionexception。要解決這個問題,需要從文檔提取節點 science:book 并將此節點用作代表(delegate)。但是這將意味著對此文檔要進行額外的解析,而且也不優雅。
提供名稱空間解析的必要性
如果 xml 使用了名稱空間,若不提供 namespacecontext,那么 xpath 表達式將會失效。清單 2 中的示例 0 充分展示了這一點。其中的 xpath 對象在所加載的 xml 文檔之上構建和求值。首先,嘗試不用任何名稱空間前綴(result1)編寫此表達式。之后,再用名稱空間前綴(result2)編寫此表達式。
清單 2. 無名稱空間解析的示例 0
private static void example0(document example) throws xpathexpressionexception, transformerexception { sysout("/n*** zero example - no namespaces provided ***"); xpath xpath = xpathfactory.newinstance().newxpath();... nodelist result1 = (nodelist) xpath.evaluate("booklist/book", example, xpathconstants.nodeset);... nodelist result2 = (nodelist) xpath.evaluate( "books:booklist/science:book", example, xpathconstants.nodeset);... } |
輸出如下所示。
清單 3. 示例 0 的輸出
*** zero example - no namespaces provided ***first try asking without namespace prefix:--> booklist/bookresult is of length 0then try asking with namespace prefix:--> books:booklist/science:bookresult is of length 0the expression does not work in both cases. |
在兩種情況下,xpath 求值并不返回任何節點,而且也沒有任何異常。xpath 找不到節點,因為缺少前綴到 uri 的映射。
硬編碼的名稱空間解析
也可以以硬編碼的值來提供名稱空間,類似于 清單 4 中的類:
清單 4. 硬編碼的名稱空間解析
public class hardcodednamespaceresolver implements namespacecontext { /** * this method returns the uri for all prefixes needed. wherever possible * it uses xmlconstants. * * @param prefix * @return uri */ public string getnamespaceuri(string prefix) { if (prefix == null) { throw new illegalargumentexception("no prefix provided!"); } else if (prefix.equals(xmlconstants.default_ns_prefix)) { return "http://univnaspresolver/book"; } else if (prefix.equals("books")) { return "http://univnaspresolver/booklist"; } else if (prefix.equals("fiction")) { return "http://univnaspresolver/fictionbook"; } else if (prefix.equals("technical")) { return "http://univnaspresolver/sciencebook"; } else { return xmlconstants.null_ns_uri; } } public string getprefix(string namespaceuri) { // not needed in this context. return null; } public iterator getprefixes(string namespaceuri) { // not needed in this context. return null; }} |
請注意名稱空間 http://univnaspresolver/sciencebook 被綁定到了前綴 technical(不是之前的 science)。結果將可以在隨后的 示例(清單 6)中看到。在 清單 5 中,使用此解析器的代碼還使用了新的前綴。
清單 5. 具有硬編碼名稱空間解析的示例 1
private static void example1(document example) throws xpathexpressionexception, transformerexception { sysout("/n*** first example - namespacelookup hardcoded ***"); xpath xpath = xpathfactory.newinstance().newxpath(); xpath.setnamespacecontext(new hardcodednamespaceresolver());... nodelist result1 = (nodelist) xpath.evaluate( "books:booklist/technical:book", example, xpathconstants.nodeset);... nodelist result2 = (nodelist) xpath.evaluate( "books:booklist/fiction:book", example, xpathconstants.nodeset);... string result = xpath.evaluate("books:booklist/technical:book/:author", example);... } |
如下是此示例的輸出。
清單 6. 示例 1 的輸出
*** first example - namespacelookup hardcoded ***using any namespaces results in a nodelist:--> books:booklist/technical:booknumber of nodes: 1<?xml version="1.0" encoding="utf-8"?> <science:book xmlns:science="http://univnaspresolver/sciencebook"> <title xmlns="http://univnaspresolver/book">learning xpath</title> <author xmlns="http://univnaspresolver/book">michael schmidt</author> </science:book>--> books:booklist/fiction:booknumber of nodes: 2<?xml version="1.0" encoding="utf-8"?> <fiction:book xmlns:fiction="http://univnaspresolver/fictionbook"> <title xmlns="http://univnaspresolver/book">faust i</title> <author xmlns="http://univnaspresolver/book">johann wolfgang von goethe</author> </fiction:book><?xml version="1.0" encoding="utf-8"?> <fiction:book xmlns:fiction="http://univnaspresolver/fictionbook"> <title xmlns="http://univnaspresolver/book">faust ii</title> <author xmlns="http://univnaspresolver/book">johann wolfgang von goethe</author> </fiction:book>the default namespace works also:--> books:booklist/technical:book/:authormichael schmidt |
如您所見,xpath 現在找到了節點。好處是您可以如您所希望的那樣重命名前綴,我對前綴 science 就是這么做的。xml 文件包含前綴 science,而 xpath 則使用了另一個前綴 technical。由于這些 uri 都是相同的,所以節點均可被 xpath 找到。不利之處是您必須要在多個地方(xml、xsd、 xpath 表達式和此名稱空間的上下文)維護名稱空間。