在C#中的变量中加载XML子节点值

问题描述 投票:0回答:1

我想要单个变量中的xml子节点值。根节点是“父节点”,主节点是“报表”。我为每个主节点“报表”编写了一个循环语句,并提取了子节点的值。

我能够循环加载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>

请让我知道我要去哪里错了?谢谢

.net xml c#-4.0 xml-parsing windows-services
1个回答
0
投票

这是您的解决方案。它显示了如何遍历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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.