[英]How to get specific value from a xml string in 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");
它沒用。我能做什么呢。
如果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>
rootElement
已經引用了<SessionInfo>
元素。 試試這種方式:
var rootElement = XElement.Parse(output);
var sessionId = rootElement.Element("SessionID").Value;
您可以按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;
試試這個方法:
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");
我希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.