如何在C#中读取XML

Vik*_*wla 0 c# xml xmlnode

这可能听起来是一个非常基本的问题,但在这里.我在DOM中加载了这个示例XML

<message from="fromvalue" to="tovalue" xml:lang="en" type="chat">
   <thread>{fe422b47-9856-4404-8c35-5ff45e43ee01}</thread> 
   <body>Test buddy</body> 
   <active xmlns="http://XXXX.org/protocol/chatstates" /> 
 </message>
Run Code Online (Sandbox Code Playgroud)

这是我从请求正文使用以下代码接收的

StreamReader reader = new StreamReader ( HttpContext.Request.InputStream,        System.Text.Encoding.UTF8 );
string sXMLRequest = reader.ReadToEnd ( );
XmlDocument xmlRequest = new XmlDocument ( );
xmlRequest.LoadXml ( sXMLRequest );
Run Code Online (Sandbox Code Playgroud)

现在我需要拥有的是三个不同变量中的三个东西的价值

string bodytext = {body element inner text}
string msgfrom = {from attribute value of message element}
string msgto =   {to attribute value of message element}
Run Code Online (Sandbox Code Playgroud)

我正在使用C#,任何人都可以从他们宝贵的时间里花一些时间来指导我,会非常感激

Jon*_*eet 5

我在这里使用LINQ to XML - 它简单:

XDocument doc = XDocument.Load(HttpContext.Request.InputStream);
string bodyText = (string) doc.Root.Element("body");
string fromAddress = (string) doc.Root.Attribute("from");
string toAddress = (string) doc.Root.Attribute("to");
Run Code Online (Sandbox Code Playgroud)

这将为您null提供任何不存在的元素/属性的值.如果您对NullReferenceException感到满意:

XDocument doc = XDocument.Load(HttpContext.Request.InputStream);
string bodyText = doc.Root.Element("body").Value;
string fromAddress = doc.Root.Attribute("from").Value;
string toAddress = doc.Root.Attribute("to").Value;
Run Code Online (Sandbox Code Playgroud)