[英]Parsing XML file in .NET
I want to get from XML file one or list of records from https://dchrs.com.pl/wp-content/themes/Lucid/doc/notowania.xml I want to get from XML file one or list of records from https://dchrs.com.pl/wp-content/themes/Lucid/doc/notowania.xml
Shortly XSD schema looks like:不久 XSD 架构看起来像:
<?xml version="1.0" encoding="utf-8"?>
<!-- Created with Liquid Technologies Online Tools 1.0 (https://www.liquid-technologies.com) -->
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="notowania">
<xs:complexType>
<xs:sequence>
<xs:element name="data_wygenerowania" type="xs:string" />
<xs:element name="kurs_euro" type="xs:decimal" />
<xs:element name="kategorie">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="kategoria">
<xs:complexType>
<xs:sequence>
<xs:element name="nazwa" type="xs:string" />
<xs:element name="pozycje">
<xs:complexType>
<xs:sequence minOccurs="0">
<xs:element maxOccurs="unbounded" name="pozycja">
<xs:complexType>
<xs:sequence>
<xs:element name="nazwa" type="xs:string" />
<xs:element name="jednostka" type="xs:string" />
<xs:element name="cena_pln" type="xs:string" />
<xs:element name="cena_euro" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
I have created a few classes like:我创建了一些类,例如:
using System.Xml.Serialization;
[XmlRoot(ElementName = "pozycja")]
public class Flower
{
[XmlElement(ElementName = "nazwa")]
public string Name { get; set; }
[XmlElement(ElementName = "jednostka")]
public string Unit { get; set; }
[XmlElement(ElementName = "cena_pln")]
public string PricePln { get; set; }
[XmlElement(ElementName = "cena_euro")]
public string PriceEuro { get; set; }
}
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot(ElementName = "pozycje")]
public class Flowers
{
[XmlElement(ElementName = "nazwa")]
public List<string> Flower { get; set; }
}
using System.Xml.Serialization;
[XmlRoot(ElementName = "kategoria")]
public class TypeOfFlower
{
[XmlElement(ElementName = "nazwa")]
public string Category { get; set; }
[XmlElement(ElementName = "pozycje")]
public Flowers Flowers { get; set; }
}
FlowerConnector
to fetch them from Url:FlowerConnector
从 Url 获取它们:using RestSharp;
using System.IO;
using System.Threading.Tasks;
using System.Xml;
using XmlSerializer = RestSharp.Serializers.XmlSerializer;
namespace FlowerShop.ApplicationServices.Components.Flowers
{
public class FlowersConnector : IFlowersConnector
{
private readonly RestClient restClient;
private readonly string baseUrl = "https://dchrs.com.pl/";
string getUrl = "https://dchrs.com.pl/wp-content/themes/Lucid/doc/notowania.xml";
public FlowersConnector()
{
this.restClient = new RestClient(baseUrl);
}
public Task<Flowers> Fetch(string name)
{
var request = new RestRequest("wp-content/themes/Lucid/doc/notowania.xml", Method.GET);
var queryResult = restClient.ExecuteAsync(request);
var flowersXml = ; // ???
}
}
}
After a few trials I got to give up.经过几次尝试,我不得不放弃。
Can somebody help me out with solving this problem?有人可以帮我解决这个问题吗?
[Edit] Here's what I've tried: [编辑]这是我尝试过的:
using RestSharp.Serialization;
using RestSharp.Serializers;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using XmlSerializer = RestSharp.Serializers.XmlSerializer;
namespace FlowerShop.ApplicationServices.Components.Flowers
{
public class FlowersConnector : IFlowersConnector
{
private readonly RestClient restClient;
private readonly string baseUrl = "https://dchrs.com.pl/";
string getUrl = "https://dchrs.com.pl/wp-content/themes/Lucid/doc/notowania.xml";
public FlowersConnector()
{
this.restClient = new RestClient(baseUrl);
}
//public async Task<Flowers> Fetch(string name)
//{
// var request = new RestRequest("wp-content/themes/Lucid/doc/notowania.xml", Method.GET);
// var queryResult = await restClient.ExecuteAsync(request);
//}
public Task<Flowers> Fetch(string name)
{
var request = new RestRequest("wp-content/themes/Lucid/doc/notowania.xml", Method.GET);
var queryResult = restClient.ExecuteAsync(request);
var flowersXml = XmlConvert<Flowers>.ListDeserializeObject(queryResult);
return new Flowers();
}
}
}
//////private readonly string apiUrl = "https://dchrs.com.pl/wp-content/themes/Lucid/doc/notowania.xml";
public class XmlConvert<T> where T : new()
{
//Serialized objects become XML strings
public static string SerializeObject(T myObj)
{
var xmlStr = string.Empty;
if (myObj != null)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter())
{
xs.Serialize(stringWriter, myObj);
xmlStr = stringWriter + "";
}
}
return xmlStr;
}
//Serialized objects become XML strings
public static string SerializeObject1(T Object)
{
var xmlStr = string.Empty;
if (Object != null)
{
XmlSerializer xs = new XmlSerializer(typeof(T));//Initializing XMLSerializer object
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
//writer.Formatting = Formatting.None;// Do not apply special format settings. This is the default value.
writer.Formatting = Formatting.Indented; //Set indent.
xs.Serialize(writer, Object);
stream.Position = 0; // Get or set the current location in the stream. Must be set, otherwise the default last position, the data in the stream is not received
using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
xmlStr += line;
}
}
writer.Close();
}
return xmlStr;
}
internal static object ListDeserializeObject(RestSharp.IRestResponse queryResult)
{
throw new System.NotImplementedException();
}
}
Shortest way to do this is use command Edit - Paste Special -> Paste XML as Clasess Then do deserialisation via XML Serializer:最短的方法是使用命令编辑 - 选择性粘贴 -> 将 XML 粘贴为类 然后通过 XML 序列化程序进行反序列化:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(notowania));
notowania n;
using (FileStream fs = new FileStream("notowania.xml", FileMode.Open))
{
n = (notowania)xmlSerializer.Deserialize(fs);
};
This give an object (Immediate Window Output)这给出了 object(立即 Window 输出)
n
{notowania}
data_wygenerowania: "2022-01-22 11:45:25"
data_wygenerowaniaField: "2022-01-22 11:45:25"
kategorie: {notowaniaKategoria[6]}
kategorieField: {notowaniaKategoria[6]}
kurs_euro: 4.53
kurs_euroField: 4.53
n.kategorie
{notowaniaKategoria[6]}
[0]: {notowaniaKategoria}
[1]: {notowaniaKategoria}
[2]: {notowaniaKategoria}
[3]: {notowaniaKategoria}
[4]: {notowaniaKategoria}
[5]: {notowaniaKategoria}
Because of your data structure consist a list inside a list one of the solutions is using the XmlArray
and XmlArrayItem
attributes.由于您的数据结构包含列表中的列表,因此解决方案之一是使用
XmlArray
和XmlArrayItem
属性。
Try the following:尝试以下操作:
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
[XmlRoot(ElementName = "notowania")]
public class Notowania
{
[XmlElement(ElementName = "data_wygenerowania")]
public string DataWygenerowania { get; set; }
[XmlElement(ElementName = "kurs_euro")]
public string KursEuro { get; set; }
[XmlArray("kategorie")]
[XmlArrayItem("kategoria")]
public List<TypeOfFlower> Flowers = new List<TypeOfFlower>();
}
[XmlRoot(ElementName = "kategoria")]
public class TypeOfFlower
{
[XmlElement(ElementName = "nazwa")]
public string Category { get; set; }
[XmlArray("pozycje")]
[XmlArrayItem("pozycja")]
public List<Flower> Items = new List<Flower>();
}
[XmlRoot(ElementName = "pozycja")]
public class Flower
{
[XmlElement(ElementName = "nazwa")]
public string Name { get; set; }
[XmlElement(ElementName = "jednostka")]
public string Unit { get; set; }
[XmlElement(ElementName = "cena_pln")]
public string PricePln { get; set; }
[XmlElement(ElementName = "cena_euro")]
public string PriceEuro { get; set; }
}
class Program
{
static void Main(string[] args)
{
Notowania result = null;
var uri = @"https://dchrs.com.pl/wp-content/themes/Lucid/doc/notowania.xml";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
using (Stream dataStream = httpResponse.GetResponseStream())
using (StreamReader streamReader = new System.IO.StreamReader(dataStream))
{
var serializer = new XmlSerializer(typeof(Notowania));
result = (Notowania)serializer.Deserialize(streamReader);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.