2014-05-20 98 views
1

我正试图使用​​Jsoup解析来自URL的XML。使用jsoup解析具有任何名称空间的文本的XML节点

在这个给定的XML中有节点与命名空间。

为前:<wsdl:types>

现在,我想它包含文本作为“类型”,但可以有任何命名空间的所有节点。

我能够得到这个节点使用表达式作为"wsdl|types"

但是我怎样才能得到所有节点包含文本作为“类型”有任何命名空间。 ?

我试着表达为"*|types",但它没有奏效。

请帮忙。

回答

3

没有这样的选择器(还)。但是你可以使用一个解决方法 - 一个不像选择器那样容易阅读,但它是一个解决方案。

/* 
* Connect to the url and parse the document; a XML Parser is used 
* instead of the default one (html) 
*/ 
final String url = "http://www.consultacpf.com/webservices/producao/cdc.asmx?wsdl"; 
Document doc = Jsoup.connect(url).parser(Parser.xmlParser()).get(); 


// Elements of any tag, but with 'types' are stored here 
Elements withTypes = new Elements(); 

// Select all elements 
for(Element element : doc.select("*")) 
{ 
    // Split the tag by ':' 
    final String s[] = element.tagName().split(":"); 

    /* 
    * If there's a namespace (otherwise s.length == 1) use the 2nd 
    * part and check if the element has 'types' 
    */ 
    if(s.length > 1 && s[1].equals("types") == true) 
    { 
     // Add this element to the found elements list 
     withTypes.add(element); 
    } 
} 

你可以把这个代码的主要部分进入一个方法,所以你得到的东西是这样的:

Elements nsSelect(Document doc, String value) 
{ 
    // Code from above 
} 

... 

Elements withTypes = nsSelect(doc, "types"); 
+0

谢谢....我会尝试这一点,并让你知道... – Pratik

+0

Supe ... working ...谢谢 – Pratik

+0

虽然这可行,但它无助于处理创建更复杂的选择器,这需要通配符命名空间匹配。我打开了一张新的票:https://github.com/jhy/jsoup/issues/723 – ericpeters

相关问题