Linq to Xml question: struggling with a simple example
I am attempting to use XML for some simple formatting and embedded links. I'm trying to parse the XML using Linq to Xml, but I'm struggling with parsing a text "Value" with embedded elements in it. For example, this might be a piece of XML I want to parse:
<description>A plain <link ID="1">table</link> with a green hat on it.</description>
Essentially, I want to enumerate through the "Runs" in the Value of the description node. In the above example, there would be a text node with a value of "A plain ", followed by a "link" element, whose value is "table", followed by another text node whose value is " with the green hat on it.".
How do I do this? I tried enumerating the root XElement's Elements() enumeration, but that only returned the link element, as did Descendants(). DescendantNod开发者_开发技巧es() did return all the nodes, but it also returned the subnodes of the link elements. In this case, a text node containing "table", in addition to the element that contained it.
You'll need to access the Nodes()
method, check the XmlNodeType
, and cast as appropriate to access each object's properties and methods.
For example:
var xml = XElement.Parse(@"<description>A plain <link ID=""1"">table</link> with a green hat on it.</description>");
foreach (var node in xml.Nodes())
{
Console.WriteLine("Type: " + node.NodeType);
Console.WriteLine("Object: " + node);
if (node.NodeType == XmlNodeType.Element)
{
var e = (XElement)node;
Console.WriteLine("Name: " + e.Name);
Console.WriteLine("Value: " + e.Value);
}
else if (node.NodeType == XmlNodeType.Text)
{
var t = (XText)node;
Console.WriteLine(t.Value);
}
Console.WriteLine();
}
XElement.Nodes() will enumerate only the top level child nodes.
Just use the Nodes()
method on your description element.
var xmlStr = @"<description>A plain <link ID=""1"">table</link> with a green hat on it.</description>";
var descriptionElement = XElement.Parse(xmlStr);
var nodes = descriptionElement.Nodes();
foreach (var node in nodes)
Console.WriteLine("{0}\t\"{1}\"", node.NodeType, node);
Yields:
Text "A plain "
Element "<link ID="1">table</link>"
Text " with a green hat on it."
精彩评论