2016-04-28 49 views
2

我有以下字符串如何從一個XML字符串特定值在C#

<SessionInfo> 
    <SessionID>MSCB2B-UKT3517_f2823910df-5eff81-528aff-11e6f-0d2ed2408332</SessionID> 
    <Profile>A</Profile> 
    <Language>ENG</Language> 
    <Version>1</Version> 
</SessionInfo> 

現在我想要得到的的SessionID。我試着用下面..

var rootElement = XElement.Parse(output);//output means above string and this step has values 

但在這裏,,

var one = rootElement.Elements("SessionInfo"); 

它沒有我不work.what能做到這一點。

而如果像below.can我們使用相同的XML字符串得到會話ID

<DtsAgencyLoginResponse xmlns="DTS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="DTS file:///R:/xsd/DtsAgencyLoginMessage_01.xsd"> 
    <SessionInfo> 
    <SessionID>MSCB2B-UKT351ff7_f282391ff0-5e81-524548a-11eff6-0d321121e16a</SessionID> 
    <Profile>A</Profile> 
    <Language>ENG</Language> 
    <Version>1</Version> 
    </SessionInfo> 
    <AdvisoryInfo /> 
</DtsAgencyLoginResponse> 

回答

5

rootElement已經引用<SessionInfo>元素。試試這個方法:

var rootElement = XElement.Parse(output); 
var sessionId = rootElement.Element("SessionID").Value; 
+1

不錯,它工作。我投了票,我會接受答案。 – bill

+0

可以請你看看第二部分 – bill

+1

@bill這是一個完全不同的問題 – HimBromBeere

0

請不要手動完成。這太可怕了。使用.NET內置的東西,使其更簡單,更可靠

XML Serialisation

這是做正確的方式。您可以創建類並讓它們從XML字符串自動序列化。

+3

'XElement'是「.NET-Stuff」並附帶LinqToXml。這樣做絕對沒問題。 – HimBromBeere

+0

好吧,Sherlock,你認爲Seriale命名空間類下面有什麼用?這是他不必寫的代碼,因爲創建類並向類和屬性添加了一些屬性。 – user853710

+0

我猜測OP只對單個值感興趣,因此他不需要創建類和添加序列化器屬性的開銷。 har07的方法很聰明,並且爲此目的很好。 – HimBromBeere

1

您可以通過XPath的選擇節點,然後獲得價值:

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(@"<SessionInfo> 
       <SessionID>MSCB2B-UKT3517_f2823910df-5eff81-528aff-11e6f-0d2ed2408332</SessionID> 
       <Profile>A</Profile> 
       <Language>ENG</Language> 
        <Version>1</Version> 
       </SessionInfo>"); 

string xpath = "SessionInfo/SessionID";  
XmlNode node = doc.SelectSingleNode(xpath); 

var value = node.InnerText; 
+0

對'String.Format'的調用在這裏完全沒有必要 –

0

試試這個方法:

private string parseResponseByXML(string xml) 
    { 
     XmlDocument xmlDoc = new XmlDocument(); 
     xmlDoc.LoadXml(xml); 
     XmlNodeList xnList = xmlDoc.SelectNodes("/SessionInfo"); 
     string node =""; 
     if (xnList != null && xnList.Count > 0) 
     { 
      foreach (XmlNode xn in xnList) 
      { 
       node= xn["SessionID"].InnerText; 

      } 
     } 
     return node; 
    } 

您的節點:

xmlDoc.SelectNodes("/SessionInfo");

不同的樣品

xmlDoc.SelectNodes("/SessionInfo/node/node"); 

我希望它有幫助。

相關問題