【问题标题】:XmlElement equivalent for ReadContentAs等效于 ReadContentAs 的 XmlElement
【发布时间】:2014-03-04 12:04:26
【问题描述】:

我正在尝试将我正在使用的XmlReader 更改为XmlDocument,但某些方法似乎不存在。我正在寻找 XmlReader.ReadContentAsXmlReader.ReadElementContentAs 的等价物。

Type myType;

if(myType == typeof(Boolean) || myType == typeof(Double))
{
    object myvalue = _cReader.ReadElementContentAs(myType, null);
}

// should become:
if(myType == typeof(Boolean) || myType == typeof(Double))
{
    object myvalue = xmlElement.ParseAnything(myType);
}

我不仅用Boolean 做这件事,而且可以用这种方式读取多种类型。 myType 也可能是 SingleDouble

【问题讨论】:

    标签: c# xmldocument xmlreader


    【解决方案1】:

    只需将XmlElement.InnerText 属性解析为特定类型:

    bool mybool = Boolean.Parse(myXmlElement.InnerText);
    

    更新:

    您可以使用Convert.ChangeType() 方法将字符串从Xml 解析为给定的Type 变量:

    Type myType;
    if(myType == typeof(Boolean) || myType == typeof(Double))
    {
        object myvalue = Convert.ChangeType(xmlElement.InnerText, myType);
    }
    

    【讨论】:

    • Boolean.Parse 是特定的,我希望它对于任何类型都是动态的。就像 ReadElementCONntentAs 一样。
    • 当您需要读取为其他类型时,只需将Boolean.Parse() 更改为OtherType.Parse()。你的意思是有多动态? ReadElementContentAs() 不是也要求你在编译时指定类型吗?
    • 我改变了我的例子。如果它是简单的原始类型,我不想为每种类型写一个新行。我真的在寻找相当于 ReadElementContentAs 的东西。
    • XmlDocumentXmlReader 有不同的方法,所以我们不能只寻找完全等效的方法。检查我的更新,有一个通用的 .NET 函数(不是来自 XmlDocument 的特定函数)可以做同样的事情。
    【解决方案2】:

    你改了 XmlReader - 为什么不改成 XDocument(这比 XmlDocument 简单多了)。

    关于你的问题,如果我理解你,你只需要Value 属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-20
      • 2019-06-29
      • 2021-09-22
      • 1970-01-01
      • 2012-02-18
      • 2017-06-20
      • 2019-05-04
      • 2016-05-10
      相关资源
      最近更新 更多