从更多xml属性中搜索值

时间:2013-12-27 19:10:09

标签: 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>

如何找到“这是样本”的最简单方法,并从第一个单词(1)中获取id?

3 个答案:

答案 0 :(得分:0)

开始使用程序化解决方案:拆分搜索字符串

var strings = searchString.Split(' ');

将计数器设置为0并开始遍历所有节点。如果您与字符串[counter]匹配,请增加计数器,否则将其重置为0.

现在从这里拿走它。

答案 1 :(得分:0)

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

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

注意:我没有测试过这个...

答案 2 :(得分:0)

这绝对是您想要的方式:

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