Reputation: 869
How do I get the top most parent element from XML? I need the entire element with its attributes.
It wont always be the first line as there might be comments.
string xmlStr = File.ReadAllText(@"C:\Users\GRPAdmin\Desktop\Test.xml");
XElement str = XElement.Parse(xmlStr);
var h1 = str.Parent;
var h2 = str.XPathSelectElements("..").FirstOrDefault();
var h3 = str.XPathSelectElement("..").Parent;
<FILE NAME="ABC" version="14.0.0.112" State="WIP" Template="ABC123" origin="designer">
<REC NAME="Recipient">
<FLD NAME="FirstName">James</FLD>
</REC>
<REC NAME="Message">
<FLD NAME="Key">123</FLD>
</REC>
<REC NAME="Details">
<FLD NAME="Key">default</FLD>
</REC>
</File>
I would expect to have a var that equals <FILE NAME="ABC" version="14.0.0.112" State="WIP" Template="ABC123" origin="designer">
as the desired result
Upvotes: 0
Views: 1071
Reputation: 615
as @har07 already said, str is the top most element. If you want the attributes just iterate over them
string xmlStr = File.ReadAllText(@"C:\Users\GRPAdmin\Desktop\Test.xml");
var root = XElement.Parse(xmlStr);
foreach (var attribute in root.Attributes())
{
Console.WriteLine("{0} : {1}", attribute .Name, attribute.Value);
}
Upvotes: 0
Reputation: 89295
In XML data model, the opening tag (including all the attributes), tag content, and the closing tag is single XML element object, so it isn't natural to request only the opening tag. I'm not aware of a bult-in .NET function to get that, but you can reconstruct the opening tag string by combining information of the tag name, and all the attribute name-value pairs, for example :
string xmlStr = File.ReadAllText(@"C:\Users\GRPAdmin\Desktop\Test.xml");
XElement str = XElement.Parse(xmlStr);
var attributes = String.Join(" ", str.Attributes().Select(o => String.Format("{0}=\"{1}\"", o.Name, o.Value)));
var result = string.Format("<{0} {1}>", str.Name, attributes);
Console.WriteLine(result);
output :
<FILE NAME="ABC" version="14.0.0.112" State="WIP" Template="ABC123" origin="designer">
Upvotes: 2
Reputation: 116794
You can use XElement.AncestorsAndSelf()
to walk up the chain of parent XML elements to the root element. Enumerable.Last
then gives you the root element:
var root = element.AncestorsAndSelf().Last();
If the XElement
is contained by some XDocument
, you can always do
var root = element.Document.Root;
But in your case you parsed directly to an XElement
without bothering to create an XDocument
container.
Upvotes: 2