【问题标题】:Using XmlTextReader to read attributes from element使用 XmlTextReader 从元素中读取属性
【发布时间】:2018-07-12 13:52:52
【问题描述】:

在下面的代码中,我找到了“Undly”元素,然后为类设置了适当的属性。这是正确的方法吗?还是我应该创建一个新的 XElement 类然后查找属性?

我仍在学习 XMLTextReader,并希望使用最佳实践。

另外,我不确定我应该使用接受 XML 文件的字符串(文件路径)的构造函数还是使用使用文件流的构造函数。似乎使用文件流的性能更快。

这里是代码

using (var fs = new FileStream(RBMRBHTheoretical, FileMode.Open, FileAccess.Read))
{
    using (var xmlReader = new XmlTextReader(fs))
    {
        while (xmlReader.Read())
        {
            if (xmlReader.NodeType == XmlNodeType.Element)
            {
                if (string.Equals(xmlReader.Name, "Undly"))
                {
                    occPLList.Add(new OccPL
                    {
                        Symbol = (string)xmlReader.GetAttribute("Sym").ToString().Trim(),
                        Description = (string)xmlReader.GetAttribute("Desc").ToString().Trim(),
                        Price = xmlReader.GetAttribute("Px") == null ? 0 : Convert.ToDecimal(xmlReader.GetAttribute("Px").ToString().Trim()),
                        Currency = (string)xmlReader.GetAttribute("Ccy").ToString().Trim()
                    });
                }
            }
        }
    } 
}

public class OccPL
{
    public string Description { get; set; }
    public decimal Price { get; set; }
    public string Currency { get; set; }
    public string Symbol { get; set; }
}

这里是xml文件:

<FIXML r="20030618" s="20040109" v="4.4" xr="FIA" xv="1" xmlns="http://www.fixprotocol.org/FIXML-4-4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://www.fixprotocol.org/FIXML-4-4 https://optionsclearing.com/components/docs/membership/dds_ref/fia_1_1/fixml-main-4-4-FIA-1-1.xsd">
 <Batch>
   <SecList ListTyp="109" ListID="20175" BizDt="2017-12-07">
     <SecL Ccy="USD">
       <Instrmt Desc="iShares S&amp;P 100 ETF" SecTyp="OPT" SubTyp="ETO" Sym="OEF" Mult="100.0">
         <AID AltID="00013" AltIDSrc="RBHP"/>
       </Instrmt>
       <InstrmtExt>
        <Attrb Typ="101" Val="1.0000"/>
        <Attrb Typ="108" Val="1.0000"/>
       </InstrmtExt>
       <Undly Desc="iShares S&amp;P 100 ETF" Px="117.110000" Ccy="USD" Sym="OEF" ID="464287101" Src="1"/>
       <Stip Typ="RBHMIN" Val="2.500"/>
       <Stip Typ="CPMMIN" Val="3.750"/>
     </SecL>
    </SecList>
  </Batch>
 </FIXML>

【问题讨论】:

  • "这是正确的做法吗?" 有效吗? “似乎使用文件流的性能更快”如果没有实际指标,就无法帮助感知性能差异。
  • 是的,它有效。我会尝试获取指标。

标签: c# filestream xmltextreader


【解决方案1】:

由于您在 FIXML 元素中有一个用于该 XML 的 XSD,我可能会使用 xsd.exe 工具从该 XSD 生成一个类,并反序列化为生成的类的实例并挑选出您自己需要的位目的。 Deserializing XML to Objects in C#

走反序列化路线是高效但严格的。如果 XML 与架构不匹配,它将中断。 XmlTextReader 和 LINQ to XML 通常会慢一些,但它们可以处理的内容更灵活。如果您打算处理大量任意 XML,那么您所做的一切都很好。如果您的 XML 将有一个明确定义的架构,那么当您可以使用 XSD 自动生成您需要的所有内容并使用反序列化器时,不要浪费您的时间编写一堆自定义反序列化代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    相关资源
    最近更新 更多