使用 C# 创建对象来表示 XML 数据
Creating object to represent XML data using C#
下面是 XML 代码。
<Shops>
<Shop>
<Location>INDIA</Location>
<Id>123</Id>
<ShopLists>
<ShopList>
<Area>500sqft</Area>
<Name>Home Decor</Name>
<LicenseNo>Ab123</LicenseNo>
</ShopList>
<ShopList>
<Area>1000sqft</Area>
<LicenseNo>Ab123</LicenseNo>
</ShopList>
</ShopLists>
</Shop>
</Shops>
由于 'shoplist' 中缺少一个数据并且结构是嵌套的,因此使用 C# 使用 Linq 创建对象在这里具有挑战性。如果找到一些关于此的输入,请回复。
我总是使用带有对象的 XmlSerializer 来执行此类任务。
参考程序集System.Xml.Serialization
using System.Xml.Serialization;
首先创建对象模型:
[XmlRoot("Shops")]
public class XmlShops
{
[XmlElement("Shop",typeof(Shop))]
public List<Shop> Shops { get; set; }
}
public class Shop
{
[XmlElement("Location")]
public string Location { get; set; }
[XmlElement("Id")]
public string Id { get; set; }
[XmlArray("ShopLists")]
[XmlArrayItem("ShopList",typeof(ShopList))]
public List<ShopList> ShopLists { get; set;}
}
public class ShopList
{
[XmlElement("Area")]
public string Area { get;set; }
[XmlElement("Home")]
public string Home { get;set; }
[XmlElement("LicenseNo")]
public string LicenseNo { get;set; }
}
然后使用Serializer 将xml 数据获取到对象模型中:
XmlSerializer ser = new XmlSerializer(typeof(XmlShops));
using (StreamReader sr = new StreamReader(@"d:\tmp\test.xml"))
{
XmlShops data = (XmlShops)ser.Deserialize(sr);
// xml should be serialized to your object model into data.
}
我鼓励您查看 http://xmltocsharp.azurewebsites.net/ 放置您的 xml,您将能够将您的 xml 表示转换为 C# 类。
然后您可以使用 XmlSerializer
将您的 xml 反序列化为特定类型,如 here 中所示。
希望对您有所帮助。
下面是 XML 代码。
<Shops>
<Shop>
<Location>INDIA</Location>
<Id>123</Id>
<ShopLists>
<ShopList>
<Area>500sqft</Area>
<Name>Home Decor</Name>
<LicenseNo>Ab123</LicenseNo>
</ShopList>
<ShopList>
<Area>1000sqft</Area>
<LicenseNo>Ab123</LicenseNo>
</ShopList>
</ShopLists>
</Shop>
</Shops>
由于 'shoplist' 中缺少一个数据并且结构是嵌套的,因此使用 C# 使用 Linq 创建对象在这里具有挑战性。如果找到一些关于此的输入,请回复。
我总是使用带有对象的 XmlSerializer 来执行此类任务。
参考程序集System.Xml.Serialization
using System.Xml.Serialization;
首先创建对象模型:
[XmlRoot("Shops")]
public class XmlShops
{
[XmlElement("Shop",typeof(Shop))]
public List<Shop> Shops { get; set; }
}
public class Shop
{
[XmlElement("Location")]
public string Location { get; set; }
[XmlElement("Id")]
public string Id { get; set; }
[XmlArray("ShopLists")]
[XmlArrayItem("ShopList",typeof(ShopList))]
public List<ShopList> ShopLists { get; set;}
}
public class ShopList
{
[XmlElement("Area")]
public string Area { get;set; }
[XmlElement("Home")]
public string Home { get;set; }
[XmlElement("LicenseNo")]
public string LicenseNo { get;set; }
}
然后使用Serializer 将xml 数据获取到对象模型中:
XmlSerializer ser = new XmlSerializer(typeof(XmlShops));
using (StreamReader sr = new StreamReader(@"d:\tmp\test.xml"))
{
XmlShops data = (XmlShops)ser.Deserialize(sr);
// xml should be serialized to your object model into data.
}
我鼓励您查看 http://xmltocsharp.azurewebsites.net/ 放置您的 xml,您将能够将您的 xml 表示转换为 C# 类。
然后您可以使用 XmlSerializer
将您的 xml 反序列化为特定类型,如 here 中所示。
希望对您有所帮助。