XDocument.Element returns null when parsing an xml string

后端 未结 4 2032
悲哀的现实
悲哀的现实 2021-01-18 09:43

I have this xml string:



        
相关标签:
4条回答
  • 2021-01-18 10:24
    var xDoc = XDocument.Load(filename);
    XNamespace ns = "http://schemas.zune.net/catalog/apps/2008/02";
    var prices = xDoc
                    .Descendants(ns + "offer")
                    .Select(o => (decimal)o.Element(ns + "price"))
                    .ToList();
    
    0 讨论(0)
  • 2021-01-18 10:25

    Here is correct way to get prices:

    var xdoc = XDocument.Parse(xmlString);
    XNamespace ns = xdoc.Root.GetDefaultNamespace();
    
    var pricres = from o in xdoc.Root.Elements(ns + "offers").Elements(ns + "offer")
                  select (int)o.Element(ns + "price");
    

    Keep in mind that your document have default namespace, and a is also namespace.

    0 讨论(0)
  • 2021-01-18 10:29

    Get the namespace somehow, like

    XNameSpace a = doc.Root.GetDefaultNamespace();

    or, probably better:

    XNameSpace a = doc.Root.GetNamespaceOfPrefix("a");
    

    and then use it in your queries:

    // to get <a:feed>
    XElement f = doc.Element(a + "feed");
    

    You can also set the namespace from a literal string, but then avoid var.

    0 讨论(0)
  • 2021-01-18 10:30

    a is a namespace. To get the feed element try this:

    XDocument doc = XDocument.Parse(xmlString);
    XNamespace a = "http://www.w3.org/2005/Atom";
    var feed = doc.Element(a + "feed");
    
    0 讨论(0)
提交回复
热议问题