使用XmlTextReader从元素读取属性

时间:2018-07-12 13:52:52

标签: c# filestream xmltextreader

在下面的代码中,我找到了“ 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>

1 个答案:

答案 0 :(得分:1)

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

采用反序列化方法是有效的,但很严格。如果XML与架构不匹配,它将中断。 XmlTextReader和LINQ to XML通常较慢,但在处理方面更灵活。如果您打算处理许多任意XML,那么您所做的一切就很好。如果您的XML将具有定义良好的架构,那么当您可以使用XSD来自动生成所需的所有内容并使用反序列化器时,不要浪费时间编写一堆自定义反序列化代码。

相关问题