Get the EndElement Node of an XElement

▼魔方 西西 提交于 2019-12-25 07:37:41

问题


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();
}

回答1:


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);
                }
            }


        }
    }
}


来源:https://stackoverflow.com/questions/40070541/get-the-endelement-node-of-an-xelement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!