c# - LINQ to XML equivalent of XPath -
i have code parses xml looks 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 find element called custom_field
has child element called column_name
value (for example bar
), , find child's sibling called column_value
, value. right use xpath on xmldocument
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 key
name of field looking for.
but want using new linq xml syntax on xdocument
. thinking move of old-style xpath parsing linq methods. maybe it's not idea, case if can work, believe have better understanding of linq in general, , able clean lot of complex code.
you can use xpath within linq xml. include system.xml.xpath
namespace.
var xpath = string.format("//custom_fields/custom_field[column_name='{0}']/column_value", key); var custom_field = doc.xpathselectelement(xpath); if (custom_field != null) { val.setvalue((int)custom_field); }
otherwise equivalent linq xml query:
var custom_field = doc.descendants("custom_fields") .elements("custom_field") .where(cf => cf.element("column_name").value == key) // assuming `key` string .elements("column_value") .singleordefault();
Comments
Post a Comment