开发者

C# class from xml

开发者 https://www.devze.com 2023-03-06 01:52 出处:网络
I am using xsd to generate classes from an xml file.It is working ok but there is one part of the xml file that is not being generated as I would like.

I am using xsd to generate classes from an xml file. It is working ok but there is one part of the xml file that is not being generated as I would like.

Here is a sample section of the xml:

<Product>
  <p0>Stapler</p0>
  <p1>1.50</p1>
  <p2&开发者_开发问答gt;0</p2>
</Product>

In the xsd that was generated form the xml, I see this section:

<xs:element name="Product" minOccurs="0" maxOccurs="unbounded">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="p0" type="xs:string" minOccurs="0" />
      <xs:element name="p1" type="xs:decimal" minOccurs="0" />
      <xs:element name="p2" type="xs:decimal" minOccurs="0" />      
    </xs:sequence>
  </xs:complexType>
</xs:element>

The problem here is that the xml responses I am trying to deserialize will have varying numbers of elements in the Product section. In the above example, it goes from p0 to p2. Other responses may go from p0 to p8.

Is there a way for me to generate a my class so that it can handle a variable number of elements for the Product?


You have two options:

  1. If you want to keep your simplicity, and the order of the elements is always the same types (so it's always string, decimal, int, etc) then just generate the schema using the Product type with all 8.

  2. Make your schema more complex, and make the "Product" a list of ProductTypes (which would define what each product is).

Something like:

<Product>
  <ProductType id="name" _type="xs:string">
       <Value>Stapler</Value>
  </ProductType>
  <ProductType id="cost" _type="xs:decimal">
       <Value>1.50</Value>
  </ProductType>
   <ProductType id="quantity" _type="xs:decimal">
       <Value>0</Value>
  </ProductType>
</Product>

It's xml so there are tons of good ways to do this.

0

精彩评论

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