Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find or create an element by xpath using LINQ-to-XML

Does anyone have a neat way of finding or creating an XObject using an xpath expression.

The problem I am having is that I need to set a value on an element (which I have the xpath for), which may or not be in existence. If it's not in existence I would like it to be created.

Any hints or links would be very much appreciated.

Thanks all.

like image 838
mileyd Avatar asked Jan 04 '11 14:01

mileyd


People also ask

How do you check if an element exists in the XML using XPath?

Use the fn:nilled XPath function to test whether the value of an input element has the xsi:nil attribute set. Use the fn:exists XPath function to test whether the value of an input element is present. Note: An XML element that has the xsi:nil attribute set is considered to be present.

Can we use LINQ for XML?

LINQ to XML is an XML programming interface. LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.

What is the use of XPath in XML?

The XML Path Language (XPath) is used to uniquely identify or address parts of an XML document. An XPath expression can be used to search through an XML document, and extract information from any part of the document, such as an element or attribute (referred to as a node in XML) in it.


1 Answers

You can use the System.Xml.XPath.Extensions class to evaluate XPath expressions on an XDocument.

http://msdn.microsoft.com/en-us/library/system.xml.xpath.extensions.aspx

For example:

using System.Xml.XPath;
...
XDocument doc = XDocument.Load("sample.xml");
var matching = doc.XPathEvaluate("//Book[@Title='Great Expectations']");  
// 'matching' could be an IEnumerable of XElements, depending on the query
like image 57
Chris Wenham Avatar answered Oct 31 '22 10:10

Chris Wenham