如何检查此xml中是否存在元素c#

时间:2013-12-20 09:48:49

标签: c# xml

我有这个问题来编程它。对于每个特定的端口元素,我想检查<script> exixst。 <script><port>节点元素的子节点。举个例子,这里是图像的链接:

http://i.stack.imgur.com/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!!
                }


            }
        }

4 个答案:

答案 0 :(得分:3)

使用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);
    }
}

答案 1 :(得分:0)

通用答案:

  • 找到<port然后找>
  • 找到</port>
  • 如果两者之间是<script,那么你就有了脚本

答案 2 :(得分:0)

也许您应该考虑使用XML Schema (XSD)并根据它验证您的XML。这应被视为最佳做法

您可以找到如何validate your XML against an XSD programatically in C#的指南。

祝你好运!

答案 3 :(得分:0)

这是一个控制台应用程序,演示了如何做到这一点:

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();
    }
}