Is there a way to get all the attributes from the xml file? XML file :
<xml>
<level1>
<login Val=“true”><\login>
<inval>hello<\inval>
<\level1>
<level2 name=“Lara”>
<input place =“VKK”> teddy string <\input>
<\level2>
I’m looking to get the xmlatributecollection which contains Val true Name Lara Place VKK
Also is it possible to get all the attributes in the child element ( element <level2 above )using childelement.attributes ? When I do this it only returns : Name Lara
But I’m expecting it to return : Name Lara Place VKK
Is it possible ? Please share ideas . Thanks
CodePudding user response:
You can use XDocument class for this purpose
using System.Xml.Linq
The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments.
You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.
var path="";//your xml file path
var xDocLoad = XDocument.Load(path);
var allAttributes = xDocLoad.Descendants()
.SelectMany(x => x.Attributes())
.ToDictionary(x => x.Name.LocalName, x => (string)x);
CodePudding user response:
First things first, your xml does not look right to me, anyway, let's assume it is something like this:
string xml = @"
<xml>
<level1>
<login Val=""true""></login>
<inval>hello</inval>
</level1>
<level2 name=""Lara"">
<input place=""VKK""> teddy string </input>
</level2>
</xml>";
You can get all attributes with corresponding names and values like this:
using System.Xml.Linq;
var doc = XDocument.Parse(xml);
var attributes = doc.Descendants()
.SelectMany(x => x.Attributes())
.ToDictionary(x => x.Name.LocalName, x => (string)x);
The result will be a dictionary with values:
Key | Value |
---|---|
Val | true |
name | Lara |
place | VKK |
DotNetFiddle example: https://dotnetfiddle.net/zBbM3Y