1

I have a XML structured like this:

<airports>
  <airport code="code">
  Airport name
    <location>Airport location</location>
   </airport>
...
</airports>

And I am trying to parse its code and name:

List<string> list = new List<string>();
XmlDocument xDoc = new XmlDocument();
xDoc.Load("file.xml");

foreach (XmlNode node in xDoc.GetElementsByTagName("airport"))
{
    list.Add(node.Attributes["code"] + " " + node.Value);
}

But instead of the value I am not getting anything. When debugging, it says, the value of the node in null. Yet, I can see the text in .InnerText. Can you tell me, where is the problem and how can I get the value?

4 Answers 4

1

Try replacing node.Value with node.FirstChild.Value.

That should return something like:

"\r\n        Airport name\r\n        "
Sign up to request clarification or add additional context in comments.

Comments

1

Well you could have probably just used innertext, but as Grant Winney alluded to the "value" of the airport node is a child node of type (text) of the airport node.

It seems strange but it was a way of dealing with xml like this

<NodeA>Fred<NodeB>Bloggs</NodeB></NodeA>

ie NodeA has two children, one of type text and another of type elements. Other node types also fit in nicely.

Comments

0

What Grant Winney said will solve your issue. But is there any reason why you're not using LINQ 2 XML instead of XmlDocument?

You can achieve what you're doing very quickly and easily with minimal code:

XDocument.Load("file.xml")
    .Root
    .Elements("airport")
    .Select (s => s.Attribute("code").Value + " " + s.FirstNode)
    .ToList<string>();


Ideally though, if you have the opportunity, you should put 'airport name' into it's own element inside <airport>. Like this:

<airports>
  <airport code="code">
    <name>Airport name</name>
    <location>Airport location</location>
   </airport>
...
</airports>

1 Comment

It does not return exactly what OP stands for.
0

The issue is that an XmlElement, which is a specialization of XmlNode where NodeType is Element, has no "value" and thus always returns null.

It has Attributes, and it has Child nodes. XmlElement.InnerText works because it recursively builds the result from the Children and grandchildren, etc (some of which are Text nodes).

Remember that text sections in XML are really just Nodes themselves.


Ideally, the XML would be fixed such that the name was an attribute (or even the sole [Text] node in an element).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.