0

I am trying to get the End node of an XElement in a C# Console application.

Say for example my XML Content is:

<Object>
  <Item>Word</Item>
  <Value>10</Value>
</Object>

How can I fetch </Object> as a node?

On iterating through element.DescendantNodesAndSelf() I still don't see isolated </Object> node.

static void Main(string[] args)
{
    const string xmlString = "<Object><Item>Word</Item><Value>10</Value></Object>";
    var element = XElement.Parse(xmlString);
    foreach (var node in element.DescendantNodesAndSelf())
    {
        Console.WriteLine($"{node}");
    }
    Console.ReadLine();
}
Nathan
  • 1,303
  • 12
  • 26
  • 1
    I maybe mistaken, but, AFAIK, end of element tag not considered as node in XML, thus no representation of it in LINQ to XML object model. But, why do you need this? What do you want to achieve? – user4003407 Oct 16 '16 at 13:30
  • @PetSerAl There's "XmlNodeType.EndElement" I wonder if that's the NodeType I am looking for. I need to get a hold of that node to perform a custom indentation on the XML content. – Nathan Oct 16 '16 at 13:56
  • As I can see `XmlNodeType.EndElement` intended for `XmlReader` to represent closing tag in XML stream, but nor XML DOM, nor LINQ to XML use that in their in-memory object models. – user4003407 Oct 16 '16 at 20:14

1 Answers1

2

I usually do the following. The ReadFrom will read past the end element.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            const string xmlString = "<Object><Item>Word</Item><Value>10</Value></Object>";
            StringReader sReader = new StringReader(xmlString);
            XmlReader xReader = XmlReader.Create(sReader);
            while (!xReader.EOF)
            {
                if (xReader.Name != "Object")
                {
                    xReader.ReadToFollowing("Object");
                }
                if (!xReader.EOF)
                {
                    XElement _object = (XElement)XElement.ReadFrom(xReader);
                }
            }


        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • Thanks but I need to maintain the XElement as such without switching to an XmlReader as the XElement is part of another XDocument and any changes I make to the XElement must reflect in the XDocument. – Nathan Oct 16 '16 at 13:51