O S
O S

Reputation: 169

C# Reading XML from url while using XMLSerializer

I have been reading How To Parse XML In .NET Core There they show an example on parsing XML using XMLSerializer.

[XmlRoot("MyDocument", Namespace = "http://www.dotnetcoretutorials.com/namespace")]
public class MyDocument
{
    public string MyProperty { get; set; }

    public MyAttributeProperty MyAttributeProperty { get; set; }

    [XmlArray]
    [XmlArrayItem(ElementName = "MyListItem")]
    public List MyList { get; set; }
}

public class MyAttributeProperty
{
    [XmlAttribute("value")]
    public int Value { get; set; }
}

and to read it:

using (var fileStream = File.Open("test.xml", FileMode.Open))
{
    XmlSerializer serializer = new XmlSerializer(typeof(MyDocument));
    var myDocument = (MyDocument)serializer.Deserialize(fileStream);

    Console.WriteLine($"My Property : {myDocument.MyProperty}");
    Console.WriteLine($"My Attribute : {myDocument.MyAttributeProperty.Value}");

    foreach(var item in myDocument.MyList)
    {
        Console.WriteLine(item);
    }
}

In the code above itreads the local xml file:

using (var fileStream = File.Open("test.xml", FileMode.Open)).

I want to read an XML file from URL, and make use of XmlSerializer, how would I accomplish this?

Upvotes: 1

Views: 1695

Answers (1)

Slava Knyazev
Slava Knyazev

Reputation: 6081

Since you already have your XML parsing logic in place, all you need is to swap out the file reading for an HTTP request.

using (var client = new HttpClient())
{
    var content = await client.GetStreamAsync("http://...");

    XmlSerializer serializer = new XmlSerializer(typeof(MyDocument));
    var myDocument = (MyDocument)serializer.Deserialize(new MemoryStream(content));

    Console.WriteLine($"My Property : {myDocument.MyProperty}");
    Console.WriteLine($"My Attribute : {myDocument.MyAttributeProperty.Value}");

    foreach(var item in myDocument.MyList)
    {
        Console.WriteLine(item);
    }
}

Upvotes: 2

Related Questions