Good day, Hashcode.

Monday is a tough day, and it looks like I finally turned over.

There is the simplest xml document:

<Шапка> <error code="40" message="Can not login." /> </Шапка> 

It is required to get "40" from there.

From my point of view, you need to get the value of the code attribute of the error element.

Type of such:

  return (from node in xdoc.Descendants() select node.Element("error").Attribute("code").Value).First(); 

Does not work. Why? How to write correctly? It’s a shame to go to StackOverflow with this question :)

And after all, this is the same thing as:

 <Шапка> <error> <code>40</code> <message>Can not login</message> </error> </Шапка> 

Right?

  • No, not the same thing, because in the first example, xml code is an attribute, and in the second example, the code is already a tag. Therefore the code that you gave for the second option is not suitable. - null
  • the logical structure is the same, but otherwise they are quite different. The second option is more preferable, as more flexible. - Sugar Sugar
  • People, I'm glad that you consider the second option (which I came up with) better than the first (which the server sends me), but I cannot take and change the structure of the answer from the server. Waiting for an answer to the question. - Olter
  • one
    Your code is working. Give the original XML. It is likely that there are declared namespaces that you do not take into account. - mantigatos

3 answers 3

So the solution.

[drumroll]

XNamespace (!) Skipped

facepalm

The decision and discussion was here

  • Isn't that your question? hashcode.ru/questions/112356 - mantigatos
  • @mantigatos, I have occasional memory lapses. :) But seriously, there really was some kind of eclipse found ... Nearly two dozen methods were written in the same class with the same namespace, but I still sat and stupid. I can not explain this. - Olter

It works for me:

 xdoc.Descendants("error").First().Attribute("code").Value; 
  • Yeah. But I - no. And they also write to me on SO that it works. So the error is somewhere else ... God knows, I will understand. - Olter
  • @Olter: see what they give out: * xdoc.Descendants("error").ToList() ? * xdoc.Descendants("error").First() ? * xdoc.Descendants("error").First().Attribute("code") ? --- Canceled, the problem, as you write, is not that. - VladD

look towards XMLTextReader from the System.Xml space

MSDN link

Link to a third-party blog

PS Try to pull the values ​​not LINQ, but in the traditional way.

  • Sorry, but this is not the answer. - Olter