How to get XElement’s value and not value of all child-nodes?

When looking for text data in the <parent> element you should look for child nodes that have NodeType properties equal to XmlNodeType.Text. These nodes will be of type XText. The following sample illustrates this: var p = XElement .Parse(“<parent>Hello<child>test1</child>World<child>test2</child>!</parent>”); var textNodes = from c in p.Nodes() where c.NodeType == XmlNodeType.Text select (XText)c; foreach (var t … Read more

Remove empty/blanks elements in collection of XML nodes

A single one-liner could do the job, no need to iterate over all elements. Here it goes: doc.Descendants().Where(e => string.IsNullOrEmpty(e.Value)).Remove(); Tester using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication1 { public class TestRemove { public static void Main() { Console.WriteLine(“—-OLD TREE STARTS—“); XElement doc = XElement.Parse(@”<magento_api> <data_item> <code>400</code> <message>Attribute … Read more

parsing XML with ampersand

Ideally the XML is escaped properly prior to your code consuming it. If this is beyond your control you could write a regex. Do not use the String.Replace method unless you’re absolutely sure the values do not contain other escaped items. For example, “wow&amp;”.Replace(“&”, “&amp;”) results in wow&amp;amp; which is clearly undesirable. Regex.Replace can give … Read more

Get the XPath to an XElement?

The extensions methods: public static class XExtensions { /// <summary> /// Get the absolute XPath to a given XElement /// (e.g. “/people/person[6]/name[1]/last[1]”). /// </summary> public static string GetAbsoluteXPath(this XElement element) { if (element == null) { throw new ArgumentNullException(“element”); } Func<XElement, string> relativeXPath = e => { int index = e.IndexPosition(); string name = e.Name.LocalName; … Read more