簡體   English   中英

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

[英]How to check if element exists in this xml c#

我有編程這個問題。 對於每個特定的端口元素,我要檢查<script>是否存在。 <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!!
                }


            }
        }

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

通用答案:

  • 找到<port ,然后>
  • 找到</port>
  • 如果之間是<script ,則您有腳本

也許您應該考慮使用XML架構(XSD)並針對它驗證XML。 這應該被視為最佳實踐

您可以找到指南,了解如何在C#中以編程方式針對XSD驗證XML

祝好運!

這是一個控制台應用程序,演示了如何完成此操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM