如何在C#中从XML字符串中获取特定值

4

我有以下字符串

<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

在这里,但需要涉及到IT技术相关内容。
var one = rootElement.Elements("SessionInfo");

它没起作用。我该怎么办。

如果以下xml字符串,我们可以使用相同的方法来获取sessionID吗?

<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>
4个回答

10

rootElement 已经引用了 <SessionInfo> 元素。请尝试以下方法:

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

1
@bill 我同意HimBromBeere的说法。无论如何,关键词是默认命名空间。第二个XML具有默认命名空间xmlns="DTS"。尝试搜索如何使用LINQ-to-XML选择命名空间中的元素... - har07

2
你可以通过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;

在这里调用 String.Format 是完全不必要的。 - Nick Mertin

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");

希望能对你有所帮助。


-1

请不要手动操作。这样太糟糕了。使用.NET内置的工具可以使它更简单和可靠。

XML序列化

这是正确的做法。你创建类并让它们自动从XML字符串中进行序列化。


4
XElement是".NET-Stuff"之一,带有LinqToXml。这样做完全没有问题。 - MakePeaceGreatAgain
我猜OP只对单个值感兴趣,因此他不需要创建类并添加序列化属性的开销。har07的方法很聪明,对于这个目的来说绝对没问题。 - MakePeaceGreatAgain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接