Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

c# - My linq-query doesn't work when adding the xmlns-attribute to the root-element in my XML-document

I'm trying to get more into LINQ-to-XML, so I've made myself a neat little example XML-document to try things out on. In addition, I tried (and successfully) made my own XML-schema for that file, just to test things out. The XML-document is pretty straightforward, and pretty much looks like this:

<cars xmlns="/carsSchema.xsd">
  <car age="5">
    <carId>1</carId>
    <brand>BMW</brand>
    <model>320i</model>
    <color paintType="metallic">Red</color>
  </car>

  <car age="2">
    <carId>2</carId>
    <brand>VW</brand>
    <model>Golf</model>
    <color paintType="matt">White</color>
  </car>
[...]
</cars>

Now, querying this document works just fine if i remove the xmlns-attribute from the root element. When i add it back in, the query returns null and nothing. I've tried to find out by myself, but I've yet to find a sollution that fixes my problem.

Here's the C#-bit:

        XDocument xmlDoc = XDocument.Load(currentDir + "\Cars.xml");

// XNamespace ns = "{" + currentDir + "\carSchema.xsd}";
// Tried to query xmlDoc.Descendants(ns+"car") after reading another post, 
// but that  made no difference

        var carInfo1 = from car in xmlDoc.Descendants("car")
                       select (string)car.Element("brand") + ": " + (string)car.Element("model");

Anyone sees what's wrong? And why should LINQ really care that much about the namespace? Can't it just query my file and don't care about it?

Thanks in advance! :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you're searching by descendants and element, you need to specify the namespace. This is pretty easy with LINQ to XML. It looks like you were nearly there, but didn't do it for the elements:

XDocument xmlDoc = XDocument.Load(currentDir + "\Cars.xml");
// I don't think namespace URIs are really resolved. I'm not sure though -
// for a proof of concept, I suggest you use a namespace of
// http://dummy.com/dummy.xsd
XNamespace ns = "/carSchema.xsd";

var carInfo1 = from car in xmlDoc.Descendants(ns + "car")
                   select (string)car.Element(ns + "brand") + ": " + 
                          (string)car.Element(ns + "model");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...