Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Parsing XML
Message
De
20/12/2014 02:24:47
 
 
À
19/12/2014 12:00:53
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Titre:
Versions des environnements
Environment:
C# 5.0
OS:
Windows Server 2008
Network:
Windows 2008 Server
Database:
MS SQL Server
Application:
Web
Divers
Thread ID:
01612438
Message ID:
01612462
Vues:
45
>I have to download some lists of codes and descriptions in XML format from a webservice and compare them with a list I'll be getting from SQL.
>Then insert or amend codes back to the web service.
>
>Any thoughts on the best way to split up xml in c# and run a process like that

If the Xml is a fairly simple list then you could deserialize to a c# list using XDocument/XmlReader/XmlSerializer. Simple console app example: Given xml:
<?xml version="1.0" encoding="utf-8" ?>
<InfoList>
  <Info>
    <Code>A1</Code>
    <Description>Something</Description>
  </Info>
  <Info>
    <Code>A2</Code>
    <Description>SomethingElse</Description>
  </Info>
  <Info>
    <Code>A3</Code>
    <Description>A Widget</Description>
  </Info>
</InfoList>
then:
using System.Xml.Linq;
using System.Xml.Serialization;

public class Program
{
    public static void Main()
    {
        var myXML = XDocument.Load("theXMLFile.xml");
        System.Xml.XmlReader reader = myXML.CreateReader();
        var s = new XmlSerializer(typeof(InfoList));
        var result = (InfoList)s.Deserialize(reader);
    }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class InfoList
{
    [System.Xml.Serialization.XmlElementAttribute("Info")]
    public Info[] Info { get; set; }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class Info
{
    public string Code { get; set; }
    public string Description { get; set; }
}
You can load the XDocument from a stream rather than a file as in my example. Also there's a little used function in VS that will create a fleshed out version of the classes for you: If you can copy an Xml example to the clipboard just set the cursor to the point where you want the class/classes to be created and use Edit/Paste Special/Paste XML as Classes.

Remember that XmlReader implements IDisposable so wrap it in a 'using'.....

HTH
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform