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
  • 您还可以生成一个 XSD 并基于 XSD 一个类来反序列化 XML(此处的简短教程
  • 您可以将 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 回答