Vladimir
Vladimir

Reputation: 1694

C# code for getting XML element by certain attribute value

I am creating XML document by reading some objects and adding them to proper place (inside xml tree structure). To be able to add it to proper place I need parent XmlNode so I could call parentNode.AppendChild(node);

How can I get XmlNode object if I know value of one of its attributes?

XmlDocument dom = new XmlDocument();
XmlNode parentNode = null;
XmlNode node = dom.CreateElement(item.Title); //item is object that I am writing to xml

XmlAttribute nodeTcmUri = dom.CreateAttribute("tcmUri");
nodeTcmUri.Value = item.Id.ToString();
node.Attributes.Append(nodeTcmUri);
parentNode = ??? - how to get XML node if I know its "tcmUri" attribute value (it is unique value, no other node has same "tcmUri" attribute value)

Upvotes: 0

Views: 1022

Answers (4)

har07
har07

Reputation: 89285

XPath is your friend :

string xpath = String.Format("//parentTag[@tcmUri='{0}']", "tcmUriValueHere");
//or in case parent node name (parentTag) may varies
//you can use XPath wildcard:
//string xpath = String.Format("//*[@tcmUri='{0}']", "tcmUriValueHere");
parentNode = dom.SelectSingleNode(xpath)

Upvotes: 0

Kiran Hegde
Kiran Hegde

Reputation: 3681

You can do this using SelectSingleNode function and xpath query as below

XmlNode parentNode = dom.SelectSingleNode("descendant::yournodename[@tcmUri='" + item.Id.ToString() + "']");

Where yournodename has to be replaced with the node name of the parent elements

Upvotes: 1

Nitin Joshi
Nitin Joshi

Reputation: 1668

Use following code:

var nodeList = doc.SelectNodes("<Node Name>[@tcmUri = \"<Value>\"]");
if(list.Count>0)
 parentNode = list[0];

Replace <Node Name> with the node name which you want to make the parent node. Replace the <Value> with the value of tcmUri attribute of the Node which you want to make the parent node.

Upvotes: 0

Sid M
Sid M

Reputation: 4354

Try this

XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
XmlNodeList  list = doc.SelectNodes("mynode");
 foreach (XmlNode item in list)
                {
                    if (item.Attributes["tcmUri"].Value == some_value)
                    {
                         // do what you want, item is the element you are looking for
                     }
                }

Upvotes: 0

Related Questions