首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XmlReader最佳实践

XmlReader最佳实践
EN

Stack Overflow用户
提问于 2011-08-28 16:35:25
回答 1查看 1.7K关注 0票数 1

我已经很好地阅读了MSDN和StackOverflow上与StackOverflow相关的问题,我还没有遇到一个像样的“最佳实践”示例。

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

XML:

代码语言:javascript
复制
<properties>
  <actions:name>start</actions:name>
  <actions:value type="System.DateTime">06/08/2011 01:26:49</actions:value>
</properties>

守则:

代码语言:javascript
复制
// 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不是选项)

EN

回答 1

Stack Overflow用户

发布于 2011-08-28 17:55:03

一种方法是使用自定义XmlReader。XmlReader是抽象的,可以将XmlReaders链接起来,这为在读取器中执行某些特定领域的处理提供了一种强大的机制。

示例:XamlXmlReader

帮助 on XmlWrappingReader

下面是如何实现它的示例(请参阅内联注释):

代码语言:javascript
复制
/// <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处理来说,这可能超出了工程的范围。除非您有更多需要自定义处理的元素,否则不建议使用这种方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7222234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档