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 myself have a small example XML - To try out documents. Apart from this, I tried (and successfully) made my own XML-schema for that file, just to check things, the XML-document is very simple, and looks much more than that:

  & lt; Cars xmlns = "/ carsSchema.xsd" & gt; & Lt; Car age = "5" & gt; & Lt; CarId> 1 & lt; / CarId> & Lt; Brand & gt; BMW & lt; / Brand & gt; & Lt; Model & gt; 320i & lt; / Model & gt; & Lt; Color paint type = "metal" & gt; Red & lt; / Color & gt; & Lt; / Car & gt; & Lt; Car Age = "2" & gt; & Lt; CarId> 2 & lt; / CarId> & Lt; Brand & gt; VW & lt; / Brand & gt; & Lt; Model & gt; Golf & lt; / Model & gt; & Lt; Color paint type = "matte" & gt; White & lt; / Color & gt; & Lt; / Car & gt; [...] & lt; / Car & gt;  

Now, if I delete the data from the xmlns - root element, then this document works properly. When I add it back, the question is empty and nothing gives. I have tried to know myself, but I still have to meet a solution that resolves my problem.

Here is the C # -Bit: XDocument xmlDoc = XDocument.Load (current DIR + "\\ car. XML"); // XNamespace ns = "{" + currentDir + "\\ carSchema.xsd}"; // After reading another post, tried to query xmlDoc.Descendants (ns + "car"), but there is no difference from the car in // xmlDoc.Descendants ("car") var select carInfo1 = (string) car. Element ("brand") + ":" + + (string) car. Element ("model");

Anyone sees what is wrong? And why should LINQ actually take great care about that namespace? Can not just check my file and do not care about it?

Thanks in advance thanks! : -)

When you are searching for ancestry and element, you must specify the namespace. It is very easy with XML from LINQ. It seems that you were almost there but did not do this for the elements:

  XDocument xmlDoc = XDocument.Load (currentDir + "\\ Cars. Xml "); // I do not think the namespace URI has actually been solved. I'm not sure - however, for a proof of // concept, I suggest that you use a // namespace of http://dummy.com/dummy.xsd XNamespace ns = "/carSchema.xsd"; Var carInfo1 = xmlDoc.Descendants (ns + "car") Select car (string) car. Element (ns + "brand") + ":" + + (string) car. Element (ns + "model");  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -