Because_i_love_you
Because_i_love_you

Reputation: 143

Get data by XPath in C#

So I have this 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>

and I want to retrieve the ChucVu tags that contain an empty TenChucVu tag so the result is this:

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

Upvotes: 2

Views: 935

Answers (4)

Les
Les

Reputation: 10605

Another XPath that should work

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

for example

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

Upvotes: 2

D T
D T

Reputation: 3746

You can as:

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

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134891

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

Upvotes: 3

MiMo
MiMo

Reputation: 11953

The XPath you need is:

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

or

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

Upvotes: 2

Related Questions