Search code examples
c#windows-phone-7xml-parsingwebservice-client

How to parse XML in a Windows Phone 7 application


Could someone tell me how to parse a XML-String that i receive from a wcf-rest service?

my webserive XML-String looks like

<WS>
    <Info>
        <Name>Beta</Name>
        <Description>Prototyps</Description>
    </Info>
    <Pages>
        <Page>
            <Name>Custom</Name>
            <Description>toDo</Description>
        </Page>
        ...many other pages...
    </Pages>
 </WS>

an my phone sourcecode:

public void DownloadCompleted(Object sender, DownloadStringCompletedEventArgs e)
{
    if (!e.Cancelled && e.Error == null)
    {
        var answer = XElement.Parse(e.Result).Descendants("WS"); // null
        ...
    }
}

if i try to parse it through XDocument.Load(e.Result) then i get the exception: File not Found.

i just want the "unique" information of the Info-Node and a list of all Page-Nodes with their values

Update Even if i try to load the Root-Element via var item = xdoc.Root.Descendants(); item will be assigned to the whole xml-file.

Update 2 it seems the problem occurs with the namespaces in the root-element. with namespaces xdocument will parse the webservice output not correctly. if i delete the namespaces it works fine. could someone explain me this issue? and is there a handy solution for deleting all namespaces?

update 3 A Handy way for removing namespaces1


Solution

  • With really simple XML if you know the format wont change, you might be interested in using XPath:

    var xdoc = XDocument.Parse(e.Result);
    var name = xdoc.XPathSelectElement("/WS/Info/Name");
    

    but for the multiple pages, maybe some linq to xml

    var xdoc = XDocument.Parse(xml);
    var pages = xdoc.Descendants("Pages").Single();
    var PagesList = pages.Elements().Select(x => new Page((string)x.Element("Name"), (string)x.Element("Description"))).ToList();
    

    Where Page is a simple class:

    public class Page
    {
        public string Name { get; set; }
        public string Descrip { get; set; }
        public Page(string name, string descrip)
        {
            Name = name;
            Descrip = descrip;
        }
    }
    

    Let me know if you need more explanation.

    Also to select the Info without XPath:

    var info = xdoc.Descendants("Info").Single();
    var InfoName = info.Element("Name").Value;
    var InfoDescrip = info.Element("Description").Value;