gpt4 book ai didi

xml - 为什么 XmlDocument 在 .NET 4 中不是动态的?

转载 作者:数据小太阳 更新时间:2023-10-29 01:42:14 26 4
gpt4 key购买 nike

我希望看到使用 dynamic 的领域之一是 XML。我认为这会使 XML 处理代码更易于编写,并且我相信在 C# 4 出现之前我已经看到了一些关于它的示例并提到了它 in this answer作为此功能的用途之一。

所以,我的问题是:为什么 XmlDocument(或 XDocument)不是动态的,或者为什么没有一些用于动态 XML 操作的新类在 C# 4 中?

这对我来说更奇怪,当我考虑在 PowerShell 中时,XmlDocument 是动态的,代码如 $xmlDoc.root.subnode.subsubnode 在那里工作。

最佳答案

令我惊讶的是,看似权威的讨论却没有答案。你的问题太棒了。它准确地解决了 dynamic 关键字的用途。问题是,真正知道如何充分利用它的人并不多。

虽然 MS 没有为我们构建动态 XML 对象,但他们确实为我们提供了使用 DynamicObject 自行构建的工具。类(class)。这是使用旧的 XmlDocument 类执行您要求的操作的一种方法。

public class DynamicXmlElement : DynamicObject {
XmlElement _xmlEl;

public DynamicXmlElement(string xml) {
var xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
_xmlEl = xmldoc.DocumentElement;
}

public DynamicXmlElement(XmlElement el) {
_xmlEl = el;
}

public override bool TrySetMember(SetMemberBinder binder, object value) {
return false;
}

public override bool TryGetMember(GetMemberBinder binder, out object result) {
XmlElement el = (XmlElement)_xmlEl.SelectSingleNode(binder.Name);
if (el != null) {
// wrap the element we found in a new DynamicXmlElement object
result = new DynamicXmlElement(el);
return true;
}
else if (binder.Name == "root") {
// special case for handling references to "root"
result = new DynamicXmlElement(_xmlEl.OwnerDocument.DocumentElement);
return true;
}
else {
// feel free to change this to prevent having accidental null reference issues
// by just setting the result to a DynamicXmlElement with a null element and
// handling _xmlEl == null at the start of this method
result = null;
return false;
}
}

public override string ToString() {
return _xmlEl.InnerText;
}
}

下面是您调用代码的方式。请注意,这只能在 C# 4.0 中编译。

namespace ConsoleApplication4 {
class Program {
static void Main(string[] args) {
var xmlstr = "<r><subnode><subsubnode>ABCs of dynamic classes</subsubnode></subnode></r>";
dynamic xml = new DynamicXmlElement(xmlstr);
Console.WriteLine(xml.subnode.root.subnode.subsubnode); // take the long way around...
Console.ReadKey(true);
}
}
}

我不能把所有的功劳都归功于此。 Bamboo wrote this code回到 2003 年的 Boo。C# 慢慢地获得了 Boo 在 .NET 中多年来所具有的特性......首先是类型推断,现在是 IQuackFu 风格的 DynamicObject。一旦他们实现了语言宏以便您可以制作 DSL,我认为他们就会 catch 来。

我将把这段代码的更新样式的 XElement 版本留给读者。

关于xml - 为什么 XmlDocument 在 .NET 4 中不是动态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3098300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com