根据特定属性值获取XML元素的c#代码

本文关键字:元素 XML 代码 获取 属性 | 更新日期: 2023-09-27 18:14:16

我通过读取一些对象并将它们添加到适当的位置(在XML树结构中)来创建XML文档。为了能够将其添加到适当的位置,我需要父XmlNode,因此我可以调用parentNode.AppendChild(node);

如果我知道XmlNode对象的一个属性的值,我怎么能得到它?

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)

根据特定属性值获取XML元素的c#代码

您可以使用如下所示的SelectSingleNode函数和xpath查询来做到这一点

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

其中yournodename必须替换为父元素的节点名称

试试这个

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

使用以下代码:

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

<Node Name>替换为父节点的节点名。将<Value>替换为要作为父节点的Node的tcmUri属性的值

XPath是您的朋友:

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)
相关文章: