LINQ to XML equivalent of XPath

I have some code that parses XML that looks like this:

<custom_fields>
  <custom_field>
      <column_name>foo</column_name>
    <column_value>0</column_value>
  <description>Submitted</description>
    <data_type>BOOLEAN</data_type>
    <length>0</length>
    <decimal>0</decimal>
  </custom_field>
  <custom_field>
    <column_name>bar</column_name>
    <column_value>0</column_value>
    <description>Validated</description>
    <data_type>BOOLEAN</data_type>
    <length>0</length>
    <decimal>0</decimal>
  </custom_field>
</custom_fields>
... more <custom_field> elements...

I want to find an element with a name custom_fieldthat has a child with a name column_namewith a specific value (for example bar), and then find that child brother called column_value, and get its value. Right now I'm using XPath XMlDocumentfor this:

string path = "//custom_fields/custom_field[column_name='" + key + "']";
XmlNode xNode = doc.SelectSingleNode(path);
if (xNode != null)
{
    XmlNode v = xNode.SelectSingleNode("column_value");
    val.SetValue(v.InnerText);
}

Where keyis the name of the field I'm looking for.

, LINQ to XML XDocument. , XPath LINQ. , , , , , LINQ .

+3
3

XPath LINQ to XML. System.Xml.XPath.

var xpath = $"//custom_fields/custom_field[column_name='{key}']/column_value";
var columnValue = doc.XPathSelectElement(xpath);
if (columnValue != null)
{
    val.SetValue((int)columnValue);
}

LINQ to XML:

var columnValue = doc.Descendants("custom_fields")
    .Elements("custom_field")
    .Where(cf => (string)cf.Element("column_name") == key) // assuming 'key' is a string
    .Elements("column_value")
    .SingleOrDefault();
+5

XQuery

//custom_fields/custom_field[column_name='key']

custom_field custom_fields, column_key "key". , column_value.

LINQ to XML :

var doc = XDocument.Load(...);

var query = from fields in doc.Descendants("custom_fields")
            from field in fields.Elements("custom_field")
            where (string)field.Element("column_name") == "key"
            select (int)field.Element("column_value");

int result = query.Single();
+1

I want to find an element called custom_field that has a child named column_name with a specific value (for example, "bar", then find that sibling column_value and get its value.

Using:

/custom_fields/custom_field[column_name = 'bar']/column_value
+1
source

Source: https://habr.com/ru/post/1793173/


All Articles