这可能听起来是一个非常基本的问题,但在这里。我在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>
我正在使用以下代码从请求正文中接收
StreamReader reader = new StreamReader ( HttpContext.Request.InputStream, System.Text.Encoding.UTF8 );
string sXMLRequest = reader.ReadToEnd ( );
XmlDocument xmlRequest = new XmlDocument ( );
xmlRequest.LoadXml ( sXMLRequest );
现在,我需要拥有的是三个不同变量中的三件事值
string bodytext = {body element inner text}
string msgfrom = {from attribute value of message element}
string msgto = {to attribute value of message element}
我正在使用C#,任何人都可以从他们宝贵的时间里花一些时间来指导我,会非常感激
答案 0 :(得分: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");
对于任何不存在的元素/属性,这将为您提供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;
答案 1 :(得分:2)
您可以使用XDocument
这是.NET 3.5中引入的新XML解析器:
XDocument doc = XDocument.Parse(sXMLRequest);
string bodytext = doc.Element("message").Element("body").Value;
string msgfrom = doc.Element("message").Attribute("from").Value;
string msgto = doc.Element("message").Attribute("to").Value;
答案 2 :(得分:0)
我更喜欢XLINQ,但在您的示例中:
XmlNode thread_node = xmlRequest.SelectSingleNode("/message/thread");
Guid thread = thread_node.InnerText;
XmlNode body_node = xmlRequest.SelectSingleNode("/message/body");
string body= body_node.InnerText;
等等...
答案 3 :(得分:-1)
在Xml和C#类之间序列化/反序列化非常容易:
http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization
你基本上创建了一个类,它包含Xml的元素和属性,坚持[XmlElement]和[XmlAttribute]属性,并使用XmlSerializer
。
还有其他选择;您已经提到的XmlReader
需要大量的工作/维护,通常只用于大型文档。我见过的其他答案使用易于使用且不使用此类代理类的更高抽象级别的读者。我想这是一个偏好问题。