【问题标题】:Loading XML child nodes value in variables in C#在 C# 中的变量中加载 XML 子节点值
【发布时间】:2020-02-02 20:25:51
【问题描述】:

我想要单个变量中的 xml 子节点值。根节点是'Parent',主节点是'Reports'。我为每个主节点'Reports'写了一个循环语句并提取子节点的值。

我能够在循环中加载 xml(带有值),但在将子节点值分配给变量时获取以下错误。

“'System.NullReferenceException' 类型的未处理异常 发生在 project.exe"

c#代码

 public Service1()
        {
            InitializeComponent();

            foreach (string file in Directory.EnumerateFiles(Project.Constants.PATHNAME, "*.xml"))
            {
                XElement ReportData = XElement.Load(file);
                var Reportinfo = ReportData.Elements("Reports");
                foreach (var Reports in Reportinfo.Nodes())
                {
                    var ReportName = Reports.Document.Element("ReportName").Value;
                    var DBExecution = Reports.Document.Element("DBExecution").Value;
                    var DBName = Reports.Document.Element("DBName").Value;
                }

                var obj = new DatabaseAction("connection1");
                var result = obj.ExecuteCommandQuery("select * from sometable");

            }

        }

这里是xml:

<?xml version="1.0" encoding="utf-8"?>
<Parent>
<Reports name="Report1">
  <ReportName>xzy</ReportName>
  <DBExecution>Yes</DBExecution>
  <DBName>sqldb0001</DBName>
  <OutputFileName>xyz_output</OutputFileName>
  <OutputFilePath>123</OutputFilePath>
</Reports>
<Reports name="Report2">
  <ReportName>asdf</ReportName>
  <DBExecution>false</DBExecution>
  <DBName>sqldb0002231</DBName>
  <OutputFileName>xyzasdf_output</OutputFileName>
  <OutputFilePath>123333</OutputFilePath>
</Reports>
</Parent>

请告诉我哪里出错了?谢谢

【问题讨论】:

  • 报告是父级的子级,您正在获取根的节点。所以使用后代: var Reportinfo = ReportData.Descendants("Reports");那么你就不需要节点了:foreach (var Reports in Reportinfo)

标签: .net xml c#-4.0 xml-parsing windows-services


【解决方案1】:

这是您的解决方案。它展示了如何遍历 Reports 片段并在循环中获取单个子元素值。

c#

void Main()
{
    const string file = @"e:\Temp\Manivannan.xml";

    string ReportName = string.Empty;
    string DBExecution = string.Empty;
    string DBName = string.Empty;

    XDocument ReportData = XDocument.Load(file);
    foreach (var Reports in ReportData.Descendants("Reports"))
    {
        ReportName = Reports.Element("ReportName").Value;
        DBExecution = Reports.Element("DBExecution").Value;
        DBName = Reports.Element("DBName").Value;
    }
}

【讨论】:

  • 谢谢@Yitzhak khabinsky。那行得通。欣赏你干净有条理的编码风格。
猜你喜欢
  • 2018-06-01
  • 1970-01-01
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
相关资源
最近更新 更多