Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从更多xml属性中搜索值_C#_Xml_Search - Fatal编程技术网

C# 从更多xml属性中搜索值

C# 从更多xml属性中搜索值,c#,xml,search,C#,Xml,Search,我有xml,例如: <text> ... <word id="1">this</word> <word id="2">is</word> <word id="3">sample</word> <word id="4">other</word> <word id="5">words</word> ... </text> 查找此示例并从

我有xml,例如:

<text>
...
  <word id="1">this</word>
  <word id="2">is</word>
  <word id="3">sample</word>
  <word id="4">other</word>
  <word id="5">words</word>
...
</text>

查找此示例并从第一个单词1获取id的最简单方法是什么?

要开始编程解决方案,请拆分搜索字符串

var strings = searchString.Split(' ');
将计数器设置为0并开始在所有节点上循环。如果与字符串[counter]匹配,请增加计数器,否则将其重置为0


现在从这里开始

听起来像是学校的作业,无论如何,像这样的事情可能会让你走:

public string GetIDValue(XDocument xDoc)
{
    foreach (var element in xDoc.Root.Elements("word"))
    {
        if (element.Value == "this")
        {   
            return element.Attribute("id").Value;
        }
    }
}

注意:我还没有测试过这个…

这肯定会以您想要的方式工作:

static void Main(string[] args)
{
    String sampleXml =
    @"<text><word id='1'>this</word>
            <word id='2'>is</word>
            <word id='3'>sample</word>
            <word id='4'>other</word>
            <word id='5'>words</word>
        </text>";
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(sampleXml);
    XmlNodeList nodeList = xmlDocument.SelectNodes("text/word");
    foreach (XmlNode node in nodeList)
    {
        Console.WriteLine(node.FirstChild.Value);
    }
    Console.WriteLine(nodeList[0].Attributes["id"].Value);
}