问题
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