开发者

XML deserialization from XSD with variable XML elements

I have been given an XSD file that represents a huge number of elements and associated attributes. I have created an CS class using xsd.exe.

The issue is that the xml that is created can contain any or all elements and attributes.

Example XML:

<App action="A" id="1" validate="yes"><ProductType id="5885"/><SpecType id="221"/><Qty>1</Qty>开发者_StackOverflow<PartType id="7212"/><Part>456789</Part></App>
<App action="A" id="2" validate="yes"><ProductType id="5883"/><Qty>1</Qty><PartType id="7211"/><Part>132465</Part></App>

Then in my code:

protected static void ImportProduct(string filename)
{
var counter = 0;
var xSerializer = new XmlSerializer(typeof(ProductList));
var fs = new FileStream(String.Format("{0}{1}", FilePath, filename), FileMode.Open);
var reader = XmlReader.Create(fs);
var items = (ProductList)xSerializer.Deserialize(reader);

foreach (var record in items.App)
{
    counter++;

    Console.Write(String.Format("{0}{1}", record.ProductType.id, Environment.NewLine));
    Console.Write(String.Format("{0}{1}", record.Part.Value, Environment.NewLine));

    *if (!record.SpecType.Value.Equals(null))
        Console.Write(String.Format("{0}{1}", record.SpecType.id, Environment.NewLine));
    else
        Console.Write(String.Format("{0}{1}", "No SpecType!", Environment.NewLine));

    if (counter == 10)
        break;
}

}

So my question is how I can check for an empty/ non-existent element, per the starred (*) line above.

I cannot change the xsd or source XML files in any way, as they are produced by major manufacturers.

Let me know if you need more information.

Thanks! Brad


Sorry, XSD.EXE and XML Serialization isn't going to deal with XML like that.

XML of that nature is created because someone thinks it should be easy for humans to read and type in. They don't think about whether machines will be able to use them. It's a mistake that you'll now have to pay for.

The best you could do would be to create an XSLT that will place the elements into some canonical order, then create an XSD representing that order and create classes from the XSD.


Once you have an XSD you could use the dataset instead of the XML Reader. Then there are a few automatic methods created to check nulls as seen in the below example.

eg. This in an example where CalcualtionAnalysisDS is the XSD.

        CalcualtionAnalysisDS ds = new CalcualtionAnalysisDS();
        ds.ReadXml("calc.xml");

        foreach (CalcualtionAnalysisDS.ReportRow row in ds.Report.Rows)
        {
            if (row.IsBestSHDSLDesignClassNull)
            {

            }
        }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜