XML to Linq getting child nodes with attribute value - c#

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']");

Related

Parsing XML using Linq in .Net with attribute prefix values

I'm a novice w/ the Linq parsing in .NET. I have probably a simple question that I'm hoping someone can quickly answer for me. I have a huge xml that I've condensed down to figure out why my query fails. I need to parse an element from the xml that's within an node containing an attribute type. The query needs to match the attribute type and return the element value for the element name. However, the problem I'm having is, my xml has d: prefixes before the attribute name and element name and my Linq query just chokes on it. If I remove the d: prefix from the xml and query string, it works and returns the correct values, but with prefixes it doesn't work. Can someone look at my Linq query and see what I'm doing wrong with the prefixes?
Condensed xml code
<root>
<Contact xmlns:c="http://test/common/1.0">
<c:IBase type="d:testInfo" xmlns:d="http://">
<d:ActivityID>00000</d:ActivityID>
</c:IBase>
<c:IBase type="d:testInfo" xmlns:d="http://">
<d:ActivityID>00001</d:ActivityID>
</c:IBase>
</Contact>
</root>
Linq Query
var node = from el in xml.Descendants("IBase")
where
el.Attribute("type").Value == "testInfo"
select el.Element("ActivityID").Value;
foreach ( String s in node )
Console.WriteLine(string.Format("Id= {0}",s));
You have two problems to address here.
You need to specify the namespace as part of the query, as Bradley Uffner mentioned in his comment.
The type actually has a "d:" in it, which is not a namespace since it is in the value of the attribute, so you need to compare against "d:testInfo" and not just "testInfo"
Try the following:
XDocument xml = XDocument.Parse(myXmlString);
XNamespace xnc = "http://test/common/1.0";
XNamespace xnd = "http://";
var node = from el in xml.Descendants(xnc + "IBase")
where
el.Attribute("type").Value == "d:testInfo"
select el.Element(xnd + "ActivityID").Value;
foreach ( String s in node )
Console.WriteLine(string.Format("Id= {0}",s));

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);
}

Getting null value from XML element with value

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

Replace XML attributes

I have an XML file, that contain IDs in an attribute called translatedID.
This attribute exists in almost every element in the doc, so instead of searching for each element one by one, I want to select all the translatedID in the document and run some code on each attribute's value.
The needed result is - replacing the translatedID with some other data.
How can I select ALL the translatedID that exists in my XML document?
Sounds like a great case for LINQ to XML:
XDocument doc = XDocument.Load("doc.xml");
var attributes = doc.Descendants().Attributes("translatedID");
foreach (var attribute in attributes)
{
attribute.Value = DoSomethingWith(attribute.Value);
}
doc.Save("transformed.xml");
(That's assuming you want to change the value of the attribute. If you want to do something else, that's doable - but you'll need to give more information.)

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