2016-04-28 54 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"); 

我希望它有帮助。

相关问题