1

I have a project where i read XML that was exported from another system. The XML looks like this:

<?xml version="1.0" encoding="ISO-8859-1"?><xmlimexport>
    <companydata/>
    <articles/>
    <customers/>
    <suppliers/>
    <orders>
        <order>
            <atOrder>
                <OOI_HEAD_DOCUMENT_NUMBER>12345</OOI_HEAD_DOCUMENT_NUMBER>
                **... more rows ...**                       
            </atOrder>
            <rows>
                <row><OOI_ROW_ARTICLE_NUMBER>12345</OOI_ROW_ARTICLE_NUMBER><OOI_ROW_ARTICLE_TEXT>SuperDuperArticleName</OOI_ROW_TEXT>**... more data...**</row>
            </rows>
        </order>
    </orders>
    <bests/>
    <invoices/>
    <supplierinvoices/>
    <pricelists/>
    <parcels/>
</xmlimexport>

So what i do is load the path to the XML file then:

XmlDocument doc = new XmlDocument();

// Load xml file
doc.Load(xmlFile);

// Read order data
XmlNodeList orderList = doc.GetElementsByTagName("order");

foreach (XmlElement order in orderList)
{
    try
    {
        // Read atOrder data (single node)
        XmlNode atOrder = order.SelectSingleNode("atOrder");

        // Read article data (one or many nodes)
        XmlNodeList articles = order.GetElementsByTagName("row");

        // Create a order
        Order customerOrder = new Order();

Then read data with:

customerOrder.CUS_ID = Convert.ToInt32(atOrder.SelectSingleNode("OOI_HEAD_DOCUMENT_NUMBER").InnerText);

But since it can be both Strings, Booleans, Datetime, Date and INT in those fields i find myself having to use Convert. very much, is this the proper way to do this or should i use a different approach?

4

2 に答える 2

2
  • you can also generate an XSD and based on an XSD a class to deserialize the XML (short tutorial here)
  • XML を直接 DataSet (.ReadXML) に読み込むことができます。
于 2012-09-14T08:51:59.517 に答える
0

LinqToXml を見てください。役立つと思います。

http://msdn.microsoft.com/en-us/library/bb387098.aspx

于 2012-09-14T08:37:14.813 に答える