Getting null value from XML element with value - c#

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?

Try replacing node.Value with node.FirstChild.Value.
That should return something like:
"\r\n Airport name\r\n "

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.

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>

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).

Related

Create tag in XML with C#

I have a very frustrating issue which I'm hoping will actually be something extremely simple. Apologies in advance if my terminology in XML files is wrong.
Basically I have a fairly simple XML file, here is an extract of one node:
<Attr num="108" name="Title" desc="The title of this file." type="s" ord="1" value="Test Title">
I can read and write the value key of the node fairly easily, but only if the value key exists.
I can use this code to write values back to the file:
XmlNode node = xmlDoc.SelectSingleNode("//ma:Attr[#name='Title']/#value", ns);
node.Value = partname.Text;
xmlDoc.Save(sympath);
However, if the XML file has the node of the correct name, but does not have a value key then it fails. For example, in some files the XML looks like this:
<Attr num="108" name="Title" desc="The title of this file." type="s" ord="1">
So I'm going round and round in circles just trying to add value="something" to that node if it doesn't already exist. Is there a way to do this? I can add child elements, but I just want to add the value in that string!
I have tried searching for an answer, but all the other similar issues seem to be about adding or modifying child elements.
Thank you,
Andrew
Actually, XmlElement.SetAttribute() alone did the job :
var node = (XmlElement)xmlDoc.SelectSingleNode("//ma:Attr[#name='Title']", ns);
node.SetAttribute("value", partname.Text);
Select parent element instead of the attribute, check if value attribute exists in that element and take action accordingly i.e add attribute or just update the value :
var node = (XmlElement)xmlDoc.SelectSingleNode("//ma:Attr[#name='Title']", ns);
var attr = node.Attributes["value"];
if(attr != null)
{
attr.Value = partname.Text;
}
else
{
node.SetAttribute("value", partname.Text);
}

XML to Linq getting child nodes with attribute value

Variations of this question have already been asked but I have not found one that can help me with the problem i am having.
Given and XML file of this format:
<TopLevel>
<SecondLevel Name="Name" Color="Blue">
<ChildNode1></ChildNode1>
<ChildNode2></ChildNode2>
</SecondLevel>
<SecondLevel Name="Name2" Color="Red">
...
</SecondLevel>
</topLevel>
I have the value to the attribute Color.
What I would like is to be able to first find the Name corresponding to that color, and then find all the childnodes.
I prefer to use Xelement over XDocument.
This is what I have attempted so far, but with no luck.
XElement xelement = XElement.Load("XmlFile.xml");
IEnumerable<XElement> Name2=
from el in xelement.Elements("SecondLevel")
where el.Attribute("Color") == "Red"
select el;
With the result of that, I will eventually want to format it into a datatable. Is this doable?
You just missing cast of attribute to string (or getting it's value directly - see notes at the end). Also you can select Name attribute value to have sequence of strings instead of XElements:
XElement xelement = XElement.Load("XmlFile.xml");
IEnumerable<string> names =
from el in xelement.Elements("SecondLevel")
where (string)el.Attribute("Color") == "Red" // here
select (string)el.Attribute("Name");
NOTE: You can also access attribute value directly with el.Attribute("Color").Value but that will throw exception if element don't have Color attribute. So casting is more safe, but accessing value can be option if you want your code to fail fast if xml is not valid.
BTW you can also use XPath to get second level elements which have required color:
IEnumerable<XElement> secondLevels =
xelement.XPathSelectElements("SecondLevel[#Color='Red']");

Saving "skipped" nodes in xml into array

In my code, I am downloading an xml file, and because one of the nodes is variable (both name and count of them), I use code like this:
XmlNodeList arrivals = airplanes.SelectNodes("/myXml/flights/*/arrivals");
Now what I need to do, is saving names of the nodes skipped by "*" into an array, or arraylist, something like that. Later I will need to use some foreach to do something with each of the nodes, now saved as strings. I have tried
foreach(* in MyArrayList)
and that doesnt work, I get a number of errors there, assuming I cant use the " * " here.
Each XmlNode in the XmlNodeList has a ParentNode property, you should be able to use that to navigate back up from the arrivals node in the xml to the * node.
The following Linq query should get the names:
var names = arrivals.Cast<XmlNode>().Select(x => x.ParentNode.Name).ToList();
The Cast<XmlNode> is needed because XmlNodeList doesn't implement the generic IEnumerable interface.

Get specific data from XML document

I have xml document like this:
<level1>
<level2>
<level3>
<attribute1>...</attribute1>
<attribute2>false</attribute2>
<attribute3>...</attribute3>
</level3>
<level3>
<attribute1>...</attribute1>
<attribute2>true</attribute2>
<attribute3>...</attribute3>
</level3>
</level2>
<level2>
<level3>
<attribute1>...</attribute1>
<attribute2>false</attribute2>
...
...
...
I'm using c#, and I want to go thru all "level3", and for every "level3", i want to read attribute2, and if it says "true", i want to print the corresponding attribute3 (can be "level3" without these attributes).
I keep the xml in XmlDocument.
Then I keep all the "level3" nodes like this:
XmlNodeList xnList = document.SelectNodes(String.Format("/level1/level2/level3"));
(document is the XmlDocument).
But from now on, I don't know exactly how to continue. I tried going thru xnList with for..each, but nothing works fine for me..
How can I do it?
Thanks a lot
Well I'd use LINQ to XML:
var results = from level3 in doc.Descendants("level3")
where (bool) level3.Element("attribute2")
select level3.Element("attribute3").Value;
foreach (string result in results)
{
Console.WriteLine(result);
}
LINQ to XML makes all kinds of things much simpler than the XmlDocument API. Of course, the downside is that it requires .NET 3.5...
(By the way, naming elements attributeN is a bit confusing... one would expect attribute to refer to an actual XML attribute...)
You can use LINQ to XML and reading this is a good start.
You can use an XPath query. This will give you a XmlNodeList that contains all <attribute3> elements that match your requirement:
var list = document.SelectNodes("//level3[attribute2 = 'true']/attribute3");
foreach(XmlNode node in list)
{
Console.WriteLine(node.InnerText);
}
You can split the above xpath query in three parts:
"//level3" queries for all descendant elements named <level3>.
"[attribute2 = 'true']" filters the result from (1) and only keeps the elements where the child element <attribute2> contains the text true.
"/attribute3" takes the <attribute3> childnode of each element in the result of (2).

Setting attributes in an XML document

I'm writing one of my first C# programs. Here's what I'm trying to do:
Open an XML document
Navigate to a part of the XML tree and select all child elements of type <myType>
For each <myType> element, change an attribute (so <myType id="oldValue"> would become <myType id="newValue">
Write this modified XML document to a file.
I found the XmlDocument.SelectNodes method, which takes an XPath expression as its argument. However, it returns an XmlNodeList. I read a little bit about the difference between an XML node and an XML element, and this seems to explain why there is no XmlNode.SetAttribute method. But is there a way I can use my XPath expression to retrieve a list of XmlElement objects, so that I can loop through this list and set the id attributes for each?
(If there's some other easier way, please do let me know.)
Simply - it doesn't know if you are reading an element or attribute. Quite possibly, all you need is a cast here:
foreach(XmlElement el in doc.SelectNodes(...)) {
el.SetAttribute(...);
}
The SelectNodes returns an XmlNodeList, but the above treats each as an XmlElement.
I am a big fan of System.Xml.Linq.XDocument and the features it provides.
XDocument xDoc = XDocument.Load("FILENAME.xml");
// assuming you types is the parent and mytype is a bunch of nodes underneath
IEnumerable<XElement> elements = xdoc.Element("types").Elements("myType");
foreach (XElement type in elements)
{
// option 1
type.Attribute("id").Value = NEWVALUE;
// option 2
type.SetAttributeValue("id", NEWVALUE);
}
Option 1 or 2 works but I prefer 2 because if the attribute doesn't exist this'll create it.
I'm sitting at my Mac so no .NET for me...
However, I think that you can cast an XmlNode to an XmlElement via an explicit cast.
You should be able to cast the XmlElement to an XmlNode then and get it's children Nodes using something like XmlNode.ChildNodes.

Categories

Resources