简体   繁体   中英

How to get value of element with XDocument and Linq to XML

I want to collect the RequestID element with the namespace, but I do not know how.

this.XmlString =  "<?xml version=\"1.0\" 
encoding=\"utf-8\"?><MethodNameRq xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" 
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><RequestID 
xmlns=\"http://Mynamespace\">573-348976-428697-346</RequestID ></MethodNameRq>";

var doc = XDocument.Parse(this.XmlString);

this.RequestId = (string)doc.Descendants().Where(n => n.Name 
                 == "RequestID ").FirstOrDefault();

This collects an empty string for RequestID . It does work if the string has no namespaces included. Does anyone know how I can collect the RequestID element?

you need to specify the namespace of your element

XNamespace ns = "http://Mynamespace";

this.RequestId = (string)doc.Descendants(ns + "RequestID").FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM