XmlReader最佳实践

时间:2011-08-28 16:35:26

标签: c# .net-2.0 xmlreader

我已经很好地阅读了关于StackOverflow的MSDN和XmlReader相关问题,我还没有遇到过一个不错的“最佳实践”示例。

我尝试过各种各样的组合,但每种组合似乎都有缺点,但我能想到的最好的组合如下:

XML:

<properties>
  <actions:name>start</actions:name>
  <actions:value type="System.DateTime">06/08/2011 01:26:49</actions:value>
</properties>

代码:

// Reads past the initial/root element
reader.ReadStartElement();

// Check we haven't hit the end
while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement) {
    if (reader.IsStartElement("name", NamespaceUri)) {
        // Read the name element
        this.name = reader.ReadElementContentAsString();
    } else if (reader.IsStartElement("value", NamespaceUri)) {
        // Read the value element
        string valueTypeName = reader["type"] ?? typeof(string).Name;
        Type valueType = Type.GetType(valueTypeName);
        string valueString = reader.ReadElementContentAsString();
        // Other stuff here that doesn;t matter to the XML parsing
    } else {
        // We can't do anything with this node so skip over it
        reader.Read();
    }
}

这是从.ReadSubTree()调用传递到我的类中,每个类都读取自己的信息。我希望它不要依赖它按特定的顺序。

在此之前,我确实尝试了几种变体。

1)while(reader.Read()) 这是从各种示例中获得的,但发现当元素1的.ReadContent*()将其留在元素2的开头时,它“遗漏”了一些元素,.Read将其读取到元素3。

2)删除.Read()导致它在我读取的第一个元素后卡住。

3)其他几个我长期以来“失败”的人。

据我所知,我已经确定的代码似乎是最接受和最稳定的代码,但有什么明显的东西我不知道了吗?

(注意c#2.0标签,因此LINQ / XNode / XElement不是选项)

1 个答案:

答案 0 :(得分:1)

一种方法是使用自定义XmlReader。 XmlReader是抽象的,XmlReaders可以链接,提供了一个强大的机制,可以在阅读器中进行一些域特定的处理。

示例:XamlXmlReader

XmlWrappingReader

上的

Help

以下是如何实施的示例(参见内联评论):

/// <summary>
/// Depending on the complexity of the Xml structure, a complex statemachine could be required here.
/// Such a reader nicely separates the structure of the Xml from the business logic dependent on the data in the Xml. 
/// </summary>
public class CustomXmlReader: XmlWrappingReader
{
    public CustomXmlReader(XmlReader xmlReader)
        :base(XmlReader.Create(xmlReader, xmlReader.Settings))
    {

    }

    public override bool Read()
    {
        var b = base.Read();
        if (!b)
            return false;
        _myEnum = MyEnum.None;
        if("name".Equals(this.Name))
        {
            _myEnum = MyEnum.Name;
            //custom logic to read the entire element and set the enum, name and any other properties relevant to your domain
            //Use base.Read() until you've read the complete "logical" chunk of Xml. The "logical" chunk could be more than a element.
        }
        if("value".Equals(this.Value))
        {
            _myEnum = Xml.MyEnum.Value;
            //custom logic to read the entire element and set the enum, value and and any other properties relevant to your domain
            //Use base.Read() until you've read the complete "logical" chunk of Xml. The "logical" chunk could be more than a element.
        }
        return true;
    }
    //These properties could return some domain specific values
    #region domain specific reader properties. 
    private MyEnum _myEnum;
    public MyEnum MyEnum
    {
        get { return _myEnum; }
    }

    #endregion
}

public enum MyEnum
{
    Name,
    Value,
    None
}

public class MyBusinessAppClass
{
    public void DoSomething(XmlReader passedInReader)
    {

        var myReader = new CustomXmlReader(passedInReader);
         while(myReader.Read())
         {
             switch(myReader.MyEnum)
             {
                 case MyEnum.Name:
                     //Do something here;
                     break;
                 case MyEnum.Value:
                     //Do something here;
                     break;

             }
         }
    }
}

请注意:对于您在此处显示的一些简单的Xml处理,这可能过于工程化。除非您有更多需要自定义处理的两个元素,否则不建议使用此方法。