@S Abijith , you could design a dynamic class to adapt your dynamic xml file.
First, you could create the following class to inherit from the class DynamicObject.
using System.Dynamic;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
string xml2 = File.ReadAllText("Issue.txt");
dynamic zabbix_export = DynamicXml.Parse(xml2);
var namelist = zabbix_export.hosts.host;
foreach (var item in namelist)
{
Console.WriteLine(item.name); //Get Device Name
}
foreach (var host in namelist)
{
foreach (var inter in host.interfaces.@interface)
{
Console.WriteLine(inter.ip); //Get ip
}
}
foreach (var host in namelist)
{
var tags = host.tags.tag;
if (tags.ToString().Contains("DynamicXml"))
{
if(tags.tag.ToString()== "Model_Name")
{
Console.WriteLine(tags.tag + "**" + tags.value); //Get tag called Model_Name and its value
}
}
else
{
var newtag = host.tags.tag;
foreach (var item in newtag)
{
if(item.tag.ToString() == "Model_Name")
{
Console.WriteLine(item.tag+"**"+item.value);
}
}
}
}
Console.ReadKey();
}
}
public class DynamicXml : DynamicObject
{
XElement _root;
private DynamicXml(XElement root)
{
_root = root;
}
public static DynamicXml Parse(string xmlString)
{
return new DynamicXml(XDocument.Parse(xmlString).Root);
}
public static DynamicXml Load(string filename)
{
return new DynamicXml(XDocument.Load(filename).Root);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
var att = _root.Attribute(binder.Name);
if (att != null)
{
result = att.Value;
return true;
}
var nodes = _root.Elements(binder.Name);
if (nodes.Count() >1)
{
result = nodes.Select(n => n.HasElements ? (object)new DynamicXml(n) : n.Value).ToList();
return true;
}
XElement node = _root.Element(binder.Name);
if (node != null)
{
result = node.HasElements || node.HasAttributes ? (object)new DynamicXml(node) : node.Value;
return true;
}
return true;
}
}
I write the comment for the specific value and you can have a look.
Updated code:
foreach (var host in namelist)
{
foreach (var inter in host.interfaces.@interface)
{
Console.WriteLine(inter.ip); //Get ip
}
}
The result is
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.