2016-10-25 63 views
0

的屬性具有XML我怎樣才能跟蹤XML

<schemans2:ServicepointForAccountRow AccountID="123456" ServicePointID="987654" 
           LongDescription="TE Fix Network RES SINGLE PHS/TEP 13 MR/FN TEP Rt 0010/3220 W INA RD, 13203, TUCSON, AZ, 85741-2169, TEP" 
           UsageInfo="Add"/> 

我想一個元素ServicePointID。

如何,我們可以使用情況跟蹤屬性事件的SERVICEPOINTFORACCOUNTROW標籤XMLStreamConstants.ATTRIBUTE

+1

歡迎,你可以看看[問]並在那之後如何創建一個[mcve] – AxelH

+0

@Hamesh檢查我的答案,如果它適合你,那麼請接受我的答案。謝謝 –

回答

1

下面是代碼

import java.util.List; 

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Node; 
import org.jsoup.parser.Parser; 

public class Test { 

    public static void main(String[] args) { 
     String xml = "<schemans2:ServicepointForAccountRow AccountID=\"123456\" ServicePointID=\"987654\" LongDescription=\"TE Fix Network RES SINGLE PHS/TEP 13 MR/FN TEP Rt 0010/3220 W INA RD, 13203, TUCSON, AZ, 85741-2169, TEP\" UsageInfo=\"Add\" />"; 
     Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); 
     List<Node> nodes = doc.childNodes(); 
     for(Node n : nodes) { 
      System.out.println(n.attr("ServicePointID")); 
     } 
    } 
} 

輸出

987654 
0

既然你提到的使用XMLStreamConstants,我假設你p lan使用XMLStreaming接口。這樣做的一個方法是如下

XMLInputFactory factory = XMLInputFactory.newInstance(); 
XMLStreamReader parser = factory.createXMLStreamReader(new StringReader(xml)); 
    while (parser.hasNext()){ 
       int event = parser.next(); 
        if (event == XMLStreamConstants.START_ELEMENT){ 
         if (parser.getLocalName().equals("schema")){ 
          String servicePointID = parser.getAttributeValue(null, "ServicePointID"); 
         if (servicePointID != null) 
          System.out.println(servicePointID); 
      } 

注意,XML的事情是沒有得到報道在流/基於事件的接口,因此我不得不抓住它使用開始元素和操作這一點。