0

----- UPDATED -----

I have a question, simple for the more experts in c# (I am a Java dissident) and I will apreciate your help to do a good thing here using the right technique and technologies.

What I need

Load a XML file from a URL. After this I need navigate between the information sets getting the data and put it into some variables.

This will be a .NET C# executable program , stand alone that other program in COBOL will run and recuperate the data.

The exemple XML is:

<?xml version="1.0" encoding="utf-8"?>
<movie>
  <title>
    Fast Five
  </title>
  <year>
    2011
  </year>
  <description>
    Dominic Toretto and his crew of street racers plan a massive heist ...
  </description>
  <director>
    <director_1>Justin Lin</director_1>
    <director_2>Vovó Mafalda</director_2>
  </director>
</movie>

Accessible in, localhost:8080\movie.xml, for example.

I have a code to load a XML:

namespace main
{
    public class XMLLoader
    {
        public static void getXMLContent()
        {
            String title = null;
            String year = null;
            String description = null;
            String director1 = null;
            String director2 = null;
            String director3 = null;

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load("http://localhost:8081/xml/movies.xml");

                title       = (xmlDoc.GetElementsByTagName("title")[0]).InnerText.Trim();
                year        = (xmlDoc.GetElementsByTagName("year")[0]).InnerText.Trim();
                description = (xmlDoc.GetElementsByTagName("description")[0]).InnerText.Trim();
                director1   = (xmlDoc.GetElementsByTagName("director_1")[0]).InnerText.Trim();
                director2   = (xmlDoc.GetElementsByTagName("director_2")[0]).InnerText.Trim();
                director3   = (xmlDoc.GetElementsByTagName("director_3")[0]).InnerText.Trim();

                Console.WriteLine("Movie......: " + title);
                Console.WriteLine("Year.......: " + year);
                Console.WriteLine("Description: " + description);
                Console.WriteLine("Director1..: " + director1);
                Console.WriteLine("Director2..: " + director2);
                Console.WriteLine("Director3..: " + director3);
            }
            catch (Exception e)
            {
                Console.WriteLine("        Error to load URL");
                Console.WriteLine("        Message: " + e.Message);
            }
        }

        static void Main(string[] args)
        {
            getXMLContent();
            Console.ReadKey();
        }
    }
}

But this smells bad for me.

There is a more efficient and beautiful way to do it? And how to load a XML from a URL in a console C# program?

Thanks for all help and attention.

1
  • The fact that you're in a console application doesn't matter. It will be handled the same way no matter where you're processing the document. It's a rather trivial point, but something I just wanted to make sure you understand as you're new to .NET. Other than that, take a look at the XDocument object, and do some research on LINQ to XML. Commented Dec 11, 2013 at 13:39

3 Answers 3

1

XmlDocument can read from a URI:

XmlDocument doc = new XmlDocument();
doc.Load("http://localhost:8080/movie.xml");
var movie = doc.SelectSingleNode("/movies/movie");

There are a few different ways of reading XML from C#. For simple, small structures (and especially remote ones), I find XmlDocument to be the shortest method.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi RGraham. I'll search how to read the document with XmlDocument. Some tip? Thanks for help me.
I would read this tutorial on XPath. Should held a lot: codeproject.com/Articles/9494/…
0

If you are using a recent version of the .NET Framework (3.5 or later I think) you can use the XDocument class which has Load and Parse methods on it. Once you have your XDocument class you can use Linq to XML to build an anonymous type to hold your data, something like:-

const string xmlData = @"<?xml version=""1.0"" encoding=""utf-8""?><movie><title>Fast Five</title><year>2011</year><description>Dominic Toretto and his crew of street racers plan a massive heist to buy their freedom while in the sights of a powerful Brazilian drug lord and a dangerous federal agent.</description><director>Justin Lin</director></movie>";

var xdoc = XDocument.Parse(xmlData);
var movie = from docRoot in xdoc.Descendants("movie")
            let titleElement = docRoot.Element("title") where titleElement != null
            let yearElement = docRoot.Element("year") where yearElement != null
            let descriptionElement = docRoot.Element("description") where descriptionElement != null
            select new
            {
                Title = titleElement.Value,
                Year = yearElement.Value,
                Description = descriptionElement.Value
            };

2 Comments

Kane, thanks for this tip. But when I try it is generated the error: Could not find an implementation of the query pattern for source type System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?
But the References in the project is ok (System.Core and System.Xml.Linq is there!)
0

You can use LinQ to XML to get the data from an XML structure. Here's an article on this. Basically if this is your XML:

<movies>
  <movie>
    <title>
      Fast Five
    </title>
    <year>
      2011
    </year>
    <description>
      Dominic Toretto and his crew of street racers plan a massive heist to buy their freedom while in the sights of a powerful Brazilian drug lord and a dangerous federal agent.
    </description>
    <director>
      Justin Lin
    </director>
  </movie>
<movies>

Your code looks like this:

XElement xelement = XElement.Load("PATH_TO_XML");
IEnumerable<XElement> movies = xelement.Elements();

foreach (var movie in movies)
{
    var title = employee.Element("title").Value);
    //and so on...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.