我想知道是否有DynamicXml的内置或开源实现?
像
这样的东西var djson = System.Web.Helpers.Json.Decode(jsonText);
int id = djson.Id;
但是对于xml字符串。
所以而不是写
xitem.Element("SomeElement")
我想要
dxitem.SomeElement
答案 0 :(得分:1)
Jon Skeet C# In Depth在第14章(C#4中关于动态行为的章节)中讨论了这个想法,以及可下载的源here。
答案 1 :(得分:0)
快速search产生了几种使用C#4动态读取和编写XML的实现:
可能还有更多
答案 2 :(得分:0)
最近我花了一些时间为我的一个项目围绕XElement
和XDocument
构建动态包装器,你可以看看它here。
理念完全相同但我将实现拆分为两个单独的类:DynamicXmlReader
和DynamicXmlWriter
,其中前者只能读取元素和属性,以后可以添加子元素和属性。如果DynamicXmlReader
无法找到合适的子元素或属性,DynamicXmlWriter
会将其添加到基础XElement
中,则[TestCase]
public void SkeetBookXmlTest()
{
string books =
@"<books>
<book name=""Mortal Engines"">
<author name=""Philip Reeve"" />
</book>
<book name=""The Talisman"">
<author name=""Stephen King"" />
<author name=""Peter Straub"" />
</book>
<book name=""Rose"">
<author name=""Holly Webb"" />
<excerpt>Rose was remembering the illustrations from Morally Instructive Tales for the Nursery.</excerpt>
</book>
</books>";
dynamic dynamicXml = XElement.Parse(books).AsDynamic();
Assert.That(dynamicXml.book[0]["name"].Value, Is.EqualTo("Mortal Engines"));
Assert.That(dynamicXml.book[0].author["name"].Value, Is.EqualTo("Philip Reeve"));
Assert.That(dynamicXml.book[2]["name"].Value, Is.EqualTo("Rose"));
Assert.That((string)dynamicXml.book[2].excerpt, Is.EqualTo("Rose was remembering the illustrations from Morally Instructive Tales for the Nursery."));
}
会引发异常。
例如,在我的两个单元测试中,我使用的是Jon Skeet的书中的样本:
[TestCase]
public void SkeetBookXmlTest()
{
// Jon Skeet in his C# in Depth used following sample
string books =
@"<books>
<book name=""Mortal Engines"">
<author name=""Philip Reeve"" />
</book>
<book name=""The Talisman"">
<author name=""Stephen King"" />
<author name=""Peter Straub"" />
</book>
<book name=""Rose"">
<author name=""Holly Webb"" />
<excerpt>Rose was remembering the illustrations from Morally Instructive Tales for the Nursery.</excerpt>
</book>
</books>";
// Lets create this data dynamically
XElement element = new XElement("books");
dynamic dynamicXml = element.AsDynamicWriter();
dynamicXml.book[0]["name"] = "Mortal Engines";
dynamicXml.book[0].author["name"] = "Philip Reeve";
dynamicXml.book[1]["name"] = "The Tailisman";
dynamicXml.book[1].author[0]["name"] = "Stephen King";
dynamicXml.book[1].author[1]["name"] = "Peter Straub";
dynamicXml.book[2]["name"] = "Rose";
dynamicXml.book[2].author["name"] = "Holly Webb";
dynamicXml.book[2].excerpt = "Rose was remembering the illustrations from Morally Instructive Tales for the Nursery.";
Console.WriteLine(element);
Assert.That(dynamicXml.book[0]["name"].Value, Is.EqualTo("Mortal Engines"));
Assert.That(dynamicXml.book[0].author["name"].Value, Is.EqualTo("Philip Reeve"));
Assert.That(dynamicXml.book[2]["name"].Value, Is.EqualTo("Rose"));
Assert.That((string)dynamicXml.book[2].excerpt, Is.EqualTo("Rose was remembering the illustrations from Morally Instructive Tales for the Nursery."));
}
或者另一个创建完全相同的xml文档的单元测试:
{{1}}