接受两个值的XmlDocument查询

本文关键字:XmlDocument 查询 两个 | 更新日期: 2023-09-27 18:14:09

如何创建以下查询

如果我有XmlDocument,它可能有以下xml

<EquipmentParameterModified dateTime="2011-04-06T12:03:10.00+01:00" parameter="ExtApp">
  <Extensions ParameterId="External App Interface" FromParameterValue="" ToParameterValue="DISABLED"/>
</EquipmentParameterModified>

我如何检查我有EquipmentParameterModified并取ParameterIdToParameterValue的值

接受两个值的XmlDocument查询

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(new StringReader(xmlstr));
XmlNode node = xmldoc.GetElementsByTagName("Extensions").Item(0);
string id =  node.Attributes["ParameterId"].Value;
string val = node.Attributes["ToParameterValue"].Value;

您是否正在尝试查找给定2个输入搜索值的元素?你希望你的输出是什么?如果您只是想看看是否有一个匹配的元素,下面的代码就可以了:

如果是,尝试这样做:

        public static void Main()
        {
            var paramId = "External App Interface";
            var toParameterValue = "DISABLED";
            var xdoc = XDocument.Parse(@"
<EquipmentParameterModified dateTime='2011-04-06T12:03:10.00+01:00' parameter='ExtApp'>
  <Extensions ParameterId='External App Interface' FromParameterValue='' ToParameterValue='DISABLED'/>
</EquipmentParameterModified>");
            var ret = xdoc.Root
                .Elements("Extensions")
                .Where(e => e.Attribute("ParameterId").Value == paramId &&
                            e.Attribute("ToParameterValue").Value == toParameterValue)
                .FirstOrDefault();
            if (ret != null)
                Console.WriteLine(ret.Name);
        }

.NET 2.0更新&XmlDocument:

        public static void Main()
        {
            var paramId = "External App Interface";
            var toParameterValue = "DISABLED";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(@"
<EquipmentParameterModified dateTime='2011-04-06T12:03:10.00+01:00' parameter='ExtApp'>
  <Extensions ParameterId='External App Interface' FromParameterValue='' ToParameterValue='DISABLED'/>
</EquipmentParameterModified>");
            XmlNode node = xmlDoc.GetElementsByTagName("Extensions")[0];
            if (node.Attributes["ParameterId"].Value == paramId &&
                node.Attributes["ToParameterValue"].Value == toParameterValue)
            {
                Console.WriteLine("Found matching node:" + node.Name);
                return;
            }
        }

我建议使用XPath获取目标元素,进行空检查,然后获取该元素的特定属性,在调用.Value属性之前对属性值进行空检查。