在C#中通过XPath获取数据

时间:2012-08-13 13:26:36

标签: c# xml xpath

所以我有这个XML:

<?xml version="1.0" encoding="utf-8"?>
<M_ChucVu>
  <ChucVu>
    <MaChucVu>1
    </MaChucVu>
    <TenChucVu>
    </TenChucVu>
  </ChucVu>
  <ChucVu>
    <MaChucVu>2
    </MaChucVu>
    <TenChucVu>
    </TenChucVu>
  </ChucVu>
  <ChucVu>
    <MaChucVu>23</MaChucVu>
    <TenChucVu>12</TenChucVu>
  </ChucVu>
  <ChucVu>
    <MaChucVu>44</MaChucVu>
    <TenChucVu>44</TenChucVu>
  </ChucVu>
</M_ChucVu>

我希望检索包含空ChucVu标记的TenChucVu代码,结果如下:

<ChucVu>
  <MaChucVu>1
  </MaChucVu>
  <TenChucVu>
  </TenChucVu>
</ChucVu>
<ChucVu>
  <MaChucVu>2
  </MaChucVu>
  <TenChucVu>
  </TenChucVu>
</ChucVu>

4 个答案:

答案 0 :(得分:3)

XDocument doc = ...;
var query = doc.XPathSelectElements("//ChucVu[TenChucVu='']");

答案 1 :(得分:2)

您需要的XPath是:

/*/ChucVu[not(string(TenChucVu))]

/*/ChucVu[string-length(TenChucVu)=0]

答案 2 :(得分:2)

另一个应该工作的XPath

/M_ChucVu[./ChucVu/TenChucVu='']

例如

        var doc = new XmlDocument();
        doc.LoadXml(yourXmlString);
        var elem = doc.DocumentElement;
        var sel = elem.SelectNodes("/M_ChucVu[./ChucVu/TenChucVu!='']");
        // print or use sel.InnerXml

答案 3 :(得分:0)

你可以:

  string xparth = String.Format("//ChucVu[TenChucVu='{0}']", '');
            XmlDocument doc = new XmlDocument();
            doc.Load("Xml");
            XmlElement root = doc.DocumentElement;
            XmlNode node = root.SelectSingleNode(xparth);
            XmlNodeList list = root.SelectNodes(xparth);