代码之家  ›  专栏  ›  技术社区  ›  bill

如何从c中的xml字符串获取特定值#

  •  3
  • bill  · 技术社区  · 8 年前

    我有以下字符串

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

    现在我想得到 价值 属于 会话ID .我试过下面的。。

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

    但在这里,,

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

    它不起作用。我能做什么呢。

    如果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>
    
    4 回复  |  直到 8 年前
        1
  •  10
  •   har07    8 年前

    rootElement 已引用 <SessionInfo> 要素请尝试以下方法:

    var rootElement = XElement.Parse(output);
    var sessionId = rootElement.Element("SessionID").Value;
    
        2
  •  2
  •   Roman    8 年前

    您可以通过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;
    
        3
  •  0
  •   rootturk    8 年前

    尝试此方法:

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

    我希望它有帮助。

        4
  •  -1
  •   user853710    8 年前

    请不要手动执行此操作。这太可怕了。使用.NET内置工具使其更简单、更可靠

    XML Serialisation

    这是正确的方法。您可以创建类,并让它们从XML字符串自动序列化。