简体   繁体   English

C#代码,用于通过某些属性值获取XML元素

[英]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). 我通过阅读一些对象并将其添加到适当的位置(在xml树结构中)来创建XML文档。 To be able to add it to proper place I need parent XmlNode so I could call parentNode.AppendChild(node); 为了能够将其添加到适当的位置,我需要父级XmlNode,因此可以调用parentNode.AppendChild(node);

How can I get XmlNode object if I know value of one of its attributes? 如果我知道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)

You can do this using SelectSingleNode function and xpath query as below 您可以使用SelectSingleNode函数和xpath查询来执行此操作,如下所示

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

Where yournodename has to be replaced with the node name of the parent elements 其中yournodename必须替换为父元素的节点名称

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

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. <Node Name>替换为要成为父节点的节点名称。 Replace the <Value> with the value of tcmUri attribute of the Node which you want to make the parent node. <Value>替换为要成为父节点的Node的tcmUri属性的值。

XPath is your friend : 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM