开发者

How do I retrieve data from an XML file?

开发者 https://www.devze.com 2023-03-12 22:19 出处:网络
I have an XML file and I want to retrieve data from it so I can store this data in my database. I\'ve searched and I found this post.

I have an XML file and I want to retrieve data from it so I can store this data in my database. I've searched and I found this post.

I don't know what the follo开发者_如何学Pythonwing means:

Create a XML schema so you can deserialize this XML into a .NET object - works best if you have tons of those files to import.

So:

  • I'd like to see some articles or examples of how to do this.
  • How do I check data that comes from an XML file?


This means that you can write a .NET object that reflects the structure of your XML file and then deserialize the XML file back to an instance of this object. For example if you have the following XML:

<User>
    <FirstName>John</FirstName>
    <LastName>John</LastName>
</User>

you could have a User class:

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and then deserialize:

var serializer = new XmlSerializer(typeof(User));
using (var reader = XmlReader.Create("test.xml"))
{
    User user = (User)serializer.Deserialize(reader);
}

You can apply attributes to the .NET object in order to control the serialization/deserialization process.

As far as the validation of the XML file is concerned you could write a XSD schema (which is a XML file) representing the data structure of your file and then validate it against this schema. This will ensure that the XML file you have as an input obeys the defined rules (it has the correct node names, required properties, ...).


You want to know about "Create a XML schema so you can deserialize this XML into a .NET object - works best if you have tons of those files to import".

Here is the link that shows you how to achieve that:

Instructions


You can create schema using Visual studio. Just open XML file with VS. Then select XML->Create schema menu.

Or you can use Xsd.exe tool :

  • First extract shema using command xsd.exe your.xml
  • Second generate classes from generated schema using command xsd.exe your.xsd /classes

And here you can find how to validate xml using xsd.

0

精彩评论

暂无评论...
验证码 换一张
取 消