2016-03-09 130 views
0

我有一个服务,它返回下面的XML作为string.I使用Xdocument解析方法和XmlDocument加载方法将字符串转换为XML。但我想解析并获得我需要用于进一步处理的状态和i_numer。可以让我指出正确的方向或提供一些提示。下面是我正在使用的xml。从内部xml中获取内容与C#中的XML解析?

我试图从Xdocument和XmlDocument中返回整个“”元素,这不是我所需要的innerxml属性。

<Report> 
    <Incidentreport Company="company1" ID="sample"> 
     <status i_number="12345678" status="sucessful" /> 
    </Incidentreport> 
</Report> 
+0

([在C#与XPathNavigator的读取XML文件]的可能的复制http://stackoverflow.com/questions/3769162/reading-xml-引用文件在-C-尖与-的XPathNavigator) – cokeman19

回答

0

下面应该工作:

string str = [string of xml goes here]; 
string i_number = string.Empty; 
XmlDocument doc = new XmlDocument(); 
doc.Load(str); 
XmlNode node = doc.SelectSingleNode("//status"); 
i_number = node.Attributes["i_number"].Value; 
0

您可以使用SelectSingleNode()其接受XPath参数一气呵成得到目标属性值*:

var raw = @"<Report> 
    <Incidentreport Company='company1' ID='sample'> 
     <status i_number='12345678' status='sucessful' /> 
    </Incidentreport> 
</Report>"; 
var doc = new XmlDocument(); 
doc.LoadXml(raw); 
var result = doc.SelectSingleNode("/Report/Incidentreport/status/@i_number"); 
Console.WriteLine(result.Value); 

dotnetfiddle demo

*)注意一下XML属性可以通过使用XPath的语法@attribute_name