0

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)
1
  • 3
    For complicated XML queries, you should consider using XPath. Commented Jul 23, 2014 at 13:10

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

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)

1 Comment

@Thanks. I wasn't yet using XPath, its really useful in situations like this one.

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.