please delete me
please delete me

Reputation: 45

How to check if element exists in this xml c#

I have this problem to programming it. For each specific port element I want check if <script> exixst. The <script> is a child of <port> node element. Take this example, here's a link to the image:

https://i.sstatic.net/T2FGr.png

 // Leggi il file xml

        XDocument xml = XDocument.Load(pathFile.Text);



        var hosts = from h in xml.Descendants("address")
                   select new
                   {
                       addr = h.Attribute("addr").Value,
                       addrtype = h.Attribute("addrtype").Value
                   };

        foreach (var host in hosts)
        {
            if (host.addrtype == "ipv4")
            {
                console.Text += host.addr + Environment.NewLine;
                console.Text += host.addrtype + Environment.NewLine;

                var ports = xml.Descendants("port");

                foreach (var port in ports)
                {
                    var script = port.Element("script");

                    var hasScriptElement = script != null;

                    ?? -> how can i get the elem pem key value? thanks!!
                }


            }
        }

Upvotes: 0

Views: 2004

Answers (4)

Aquila Sands
Aquila Sands

Reputation: 1471

Here is a console app that demonstrates how this could be done:

class Program
{
    static void Main(string[] args)
    {
        string fileName = "c:\path\to\file\test.xml";
        var xmlDoc = new XmlDocument();
        xmlDoc.Load(File.OpenRead(fileName));
        XmlNodeList nodeList = xmlDoc.GetElementsByTagName("port");
        XmlNodeReader nodeReader;
        foreach (var node in nodeList)
        {
            using(nodeReader = new XmlNodeReader((XmlNode)node))
            {
                if(nodeReader.ReadToDescendant("script"))
                {
                    Console.WriteLine("Found script tag");
                }
            }
        }
        Console.ReadKey();
    }
}

Upvotes: 0

Fenton
Fenton

Reputation: 251242

Using an XDocument...

var ports = document.Descendants("port");

foreach (var port in ports) {
    var script = port.Element("script");

    if (script != null)
    {
        var pem = script.Descendants("elem")
            .FirstOrDefault(n => n.Attribute("pem") != null);
    }
}

Upvotes: 3

ˈvɔlə
ˈvɔlə

Reputation: 10272

Maybe you should consider using an XML Schema (XSD) and validate your XML against it. This should be considered as best practice!

You can found a guide how to validate your XML against an XSD programatically in C#.

Good luck!

Upvotes: 0

Sinatr
Sinatr

Reputation: 22008

Generic answer:

  • find <port and then >
  • find </port>
  • if between is a <script, then you have script

Upvotes: 0

Related Questions