从元素

时间:2016-06-01 23:51:34

标签: c# xml-parsing

我正在提供以下XML,无法更改结构:

<ReportSpec>
  <Report ReportName="ReportName1" FilterMode="Container" Destination="EmailToUser:LoggedInUser" Format="PDF" AlertSource="ALL" CriticalStatus="True">
    <Filter Students="ALL" />
  </Report>
  <Report ReportName="ReportName1" FilterMode="Container" Destination="EmailToUserGroup:UserAdmins" Format="PDF" AlertSource="ALL" CriticalStatus="False">
    <Filter TestScore="1234" />
  </Report>
  <Report ReportName="ReportName1" FilterMode="Container" Destination="Dir:\\net.path.com\reports" Format="PDF" AlertSource="Failing">
    <Filter Grade="ALL" />
  </Report>
  <Report ReportName="ReportName1" FilterMode="Container" Destination="EmailTo:a@b.com,joe@schmoe.com" Format="PDF" AlertSource="Failing">
    <Filter Course="Programming" />
  </Report>
</ReportSpec>

我正在使用C#(.NET 4.5),并且需要获取<FILTER>元素的属性名称和值,因为它们将在稍后的代码中成为app逻辑的一部分(也就是说,我想要收集TestScore="1234"作为整个字符串,并在以后使用它。我目前正在使用XMLSerializerStreamReader来加载XML文档(但如果需要,我愿意改变我的方法)。我在Visual Studio 2013中完成了PASTE SPECIAL --> XML to Classes,但是创建的Filters类不允许我对元素执行foreach。可以这样做,怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用XmlDocument类

using System;
using System.IO;
using System.Xml;

namespace ConsoleApplication1 {
class Program {
    static void Main(string[] args) {
        var file = File.ReadAllText("c:\\temp\\file.xml");
        var xmlFile = new XmlDocument();
        xmlFile.LoadXml(file);

        var filterElements = xmlFile.GetElementsByTagName("Filter");
        foreach (XmlNode filterNode in filterElements) {
            var filterName = filterNode.Attributes[0].Name;
            var filterText = filterNode.Attributes[0].InnerXml;
            var destination = filterNode.ParentNode.Attributes["Destination"].InnerText;
            var message = string.Format("the destination {0} will filter {1} by {2}", destination, filterName, filterText);
            Console.WriteLine(message);
        }
        Console.ReadKey();
    }
}

输出将是:

目的地EmailToUser:LoggedInUser将按所有人筛选学生

目标EmailToUserGroup:UserAdmins将按1234过滤TestScore

目的地Dir:\ net.path.com \ reports将按所有过滤等级

目的地EmailTo:a @ b.com,joe @ schmoe.com将过滤编程课程

答案 1 :(得分:0)

试试xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XElement reportSpec = XElement.Load(FILENAME);

            var reports = reportSpec.Elements("Report").Where(x => x.Element("Filter").Attribute("TestScore") != null).FirstOrDefault();

            int score = (int)reports.Element("Filter").Attribute("TestScore");
        }
    }
}