XPathSelectElement如何工作? C#

时间:2010-07-06 13:37:38

标签: c# xml

我遇到了以下问题。我有一个像这样的xml文件:

<Source Name ="ClassificationManager">
  <Table Name ="PositiveRegex">
    <Row>
      <Field Name="RegexPattern">^.*$</Field>
      <Field Name="Fraction">5.1</Field>
      <Field Name="ClassificationTypeNumber">1</Field>
    </Row>
    <Row>
      <Field Name="RegexPattern">^.*$</Field>
      <Field Name="Fraction">0.1</Field>
      <Field Name="ClassificationTypeNumber">2</Field>
    </Row>
  </Table>

  <Table Name ="NegativeRegex">
    <Row>
      <Field Name="RegexPattern">^.*$</Field>
      <Field Name="ClassificationTypeNumber">1</Field>
    </Row>
    <Row>
      <Field Name="RegexPattern">^.*$</Field>
      <Field Name="ClassificationTypeNumber">2</Field>
    </Row>
  </Table>

</Source>

和C#程序:

    XDocument doc = XDocument.Load(@"C:\Repository.xml");

    XElement element = doc.XPathSelectElement(@"//Source[@Name='ClassificationManager']/Table[@Name='NegativeRegex']");

    foreach (var xmlRow in element.Elements("Row"))
    {
        Console.WriteLine(xmlRow.XPathSelectElement(@"//Field[@Name='ClassificationTypeNumber']").Value);
    }

输出为1, 1但不是我想要的1, 2。怎么了?如何修改C#代码以获得我需要的东西?
谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

Console.WriteLine(xmlRow.XPathSelectElement(@"//Field[@Name='ClassificationTypeNumber']").Value);

必须是:

Console.WriteLine(xmlRow.XPathSelectElement(@"/Field[@Name='ClassificationTypeNumber']").Value);

//从根目录中选择,而不是当前元素。