【问题标题】:Validate Presence of XML Element in a XML file验证 XML 文件中是否存在 XML 元素
【发布时间】:2019-09-23 08:56:56
【问题描述】:

我有一个如下所示的 XML 文件,

<?xml version="1.0"?>
<MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Items>
    <Settings xsi:type="FileModel">
      <Name>FileOne</Name>
      <IsActive>true</IsActive>
      <IsHidden>false</IsHidden>
    </Settings>
    <Settings xsi:type="FileModel">
      <Name>FileTwo</Name>
      <IsActive>true</IsActive>
      <IsHidden>false</IsHidden>
    </Settings> 
   <Settings xsi:type="ServerModel">
      <Name>DelRep</Name>
      <IsActive>false</IsActive>
      <IsHidden>false</IsHidden>
    </Settings>
  </Items>
  <DirectoryPath>D:\MainFolder</DirectoryPath>
</MainClass>

我正在使用以下代码提取一些数据,

XDocument File = XDocument.Load(path);
XElement element = File .Root.Elements().Single(x => x.Name == "DirectoryPath");
string usingPath = element.Value;

我一直在尝试向上述代码添加某种验证,这样即使在 xml 文件缺少部分 &lt;DirectoryPath&gt;D:\MainFolder&lt;/DirectoryPath&gt; 的情况下,我也不会收到错误“sequence contains no matching element "。

在 C# 中是否有类似于可能是 Path.Exist 的属性来验证 XML 元素的存在

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

    您可以使用SingleOrDefault,如果找不到元素,则返回默认值

    XElement element = File .Root.Elements().SingleOrDefault(x => x.Name == "DirectoryPath");
    if(element != null)
    {
        string usingPath = element.Value;
    }
    

    【讨论】:

    • 如代码中所述,您可以在分配值之前使用空检查。
    【解决方案2】:

    使用:SignleOrDefault。然后你会得到正确的 XElement 或 null。

    【讨论】:

      【解决方案3】:

      没有默认方法来验证给定节点是否存在。但是我们可以使用扩展方法来实现。

      public static class XElementExtension
      {
          public static bool HasElement(this XElement xElement, string elementName)
          {
              return xElement.Elements(elementName).Any();
          }        
      }
      
      // Main
      var xmlDocument = XElement.Load(@"TestFile.xml", LoadOptions.None); 
      string elementName = "DirectoryPath";
      bool hasElement = xmlDocument.HasElement(elementName);
      if(hasElement)
      {
          Console.WriteLine(xmlDocument.Elements(elementName).First().Value);
      }
      

      【讨论】:

        猜你喜欢
        • 2018-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-11
        • 1970-01-01
        • 2020-10-22
        • 2021-04-18
        相关资源
        最近更新 更多