c# - using XmlSerializer with unknown root element
问题描述
I have some XML files that look like this:
File "B156.xml"
<B156>
<Customer>
<Name>The Barn</Name>
<Phone>0427825166</Phone>
</Customer>
<Orders>
<Item>
<Description>Black toner</Description>
<Amount>$59.00</Amount>
</Item>
<Orders>
</B156>
File "B172.xml"
<B172>
<Customer>
<Name>Pixie Inc</Name>
<Phone>0426553190</Phone>
</Customer>
<Orders>
<Item>
<Description>Colour toner</Description>
<Amount>$79.00</Amount>
</Item>
<Orders>
</B172>
How do I use XmlSerializer in this case, considering the root element is dynamic and we cannot use XmlRoot("RootName") to specify it?
解决方案
You can try this,
CLASS OBJECT
[XmlRoot("root")]
public class CustomerOrder
{
public Customer Customer { get; set; }
[XmlArray("Orders")]
[XmlArrayItem("Item")]
public List<Order> Orders { get; set; }
}
public class Customer
{
public string Name { get; set; }
public string Phone { get; set; }
}
public class Order
{
public string Description { get; set; }
public string Amount { get; set; }
}
CHANGEROOT METHOD
private static XmlDocument changeRoot(XmlDocument xmlDocument)
{
var newXmlDocument = new XmlDocument();
var newRoot = newXmlDocument.CreateElement("root");
newXmlDocument.AppendChild(newRoot);
newRoot.InnerXml = xmlDocument.DocumentElement.InnerXml;
return newXmlDocument;
}
SERIALIZATION
var xmlDocument = new XmlDocument();
xmlDocument.Load("XMLFile1.xml");
xmlDocument = changeRoot(xmlDocument);
XmlSerializer serializer = new XmlSerializer(typeof(CustomerOrder));
CustomerOrder result;
using (TextReader reader = new StringReader(xmlDocument.InnerXml))
{
result = (CustomerOrder)serializer.Deserialize(reader);
}
推荐阅读
- python - Scrapy 不从 css 路径返回数据
- r - 如何对数据框的每一列应用不同的条件?
- c++ - 如何在gdb的调用命令中使用C++默认参数
- swift - 使用 Swift 获取字体字形指标
- nsis - NSIS:使用通配符查找注册表项
- sql - 有没有办法建立三元关系,其中三个实体之一一次只与另外两个实体中的一个相关联?
- powershell - 通过 Powershell 上传 HTTP 文件
- scala - 从参数化函数中获取参数化特征的具体实现
- c# - 在自定义用户控件代码中访问已转换的 ItemsSource 对象
- ruby - 我无法在 sublime Text 3 中运行 ruby 文件