【问题标题】:Get XML attribute and value from elements从元素中获取 XML 属性和值
【发布时间】:2016-06-02 08:39:31
【问题描述】:

我收到了以下 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),需要获取&lt;FILTER&gt;元素的属性名称和值,因为它们将在代码中成为应用程序逻辑的一部分(即我想收集TestScore="1234" 作为整个字符串,稍后使用)。我目前正在使用XMLSerializerStreamReader 加载XML 文档(但如果需要,我愿意改变我的方法)。我已经在 Visual Studio 2013 中完成了 PASTE SPECIAL --&gt; XML to Classes,但是创建的 Filters 类不允许我对元素执行 foreach。这可以做到吗?如何做到?

【问题讨论】:

    标签: c# xml-parsing


    【解决方案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 将按 ALL 过滤学生

    目标 EmailToUserGroup:UserAdmins 将按 1234 过滤 TestScore

    目标目录:\net.path.com\reports 将按 ALL 过滤等级

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

    【讨论】:

    • 您可以使用 XPATH 获取所有 Filter 元素,例如 xmlFile.SelectNodes("//Filter[@TestScore]") 将返回所有具有 TestScore 属性的 Filter 元素
    • 真的没有办法绕过硬编码元素吗?对我来说,硬编码一直是一个很大的禁忌。
    【解决方案2】:

    试试 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");
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 2017-12-23
      • 2021-08-26
      • 1970-01-01
      • 2021-07-16
      相关资源
      最近更新 更多