2012-03-14 7 views
0

属性にアクセスできるコレクションがあるように、C#プロジェクトに読み込む必要がある次のxmlファイルがあります。私は遠くにはいないが、いくつかの試みを試みた。前に見たことがあるが、複製できないxmlを表すためにクラスを使用したいと思います。私はストリームリーダにファイルを読み込んで値を取り出すのは嫌です。以前のプロジェクトでは、クラスの[Serializable]属性を使用していたと思います。C#4.0を使用して必要なXmlファイルのクラス表現

希望すると便利ですか?もっと必要な場合は、C#4.0を使用しています。

おかげで、 ジェームズ

<MyProducts xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 

<MyProduct MyProductCode="MBB" MyProductCategory="Computer" MyProductMaxNumber = "4"> 
    <MyProductLookups> 
    <MyProductLookup Lang="AAA">Test 1</MyProductLookup> 
    <MyProductLookup Lang="BBB">Test 2</MyProductLookup> 
    <MyProductLookup Lang="CCC">Test 3</MyProductLookup> 
    <MyProductLookup Lang="DDD">Test 4</MyProductLookup> 
    </MyProductLookups> 
</MyProduct>  
<MyProduct MyProductCode="LJJ" MyProductCategory="Laptop" MyProductMaxNumber = "4"> 
    <MyProductLookups> 
    <MyProductLookup Lang="AAA">Test 5</MyProductLookup> 
    <MyProductLookup Lang="BBB">Test 6</MyProductLookup> 
    <MyProductLookup Lang="CCC">Test 7</MyProductLookup> 
    <MyProductLookup Lang="DDD">Test 8</MyProductLookup> 
    </MyProductLookups> 
</MyProduct> 

答えて

0

は、あなたのXMLファイルとクラスのスキーマを生成するために、Xsd.exeでは見てみましょう。

はconvetionsが一致したときに、シリアライズ可能なもののみ正しく動作Generate classes from XSDUsing XSD Tool to Generate Classes from XML

+0

xmlをオブジェクトにシリアル化するためのC#コード(以前はツールを使用したとは思わない) –

+0

はい - このツールはXMLファイルの構造を表すクラスのコードを生成するので、それらを書く必要がありません。 2番目のリンクを見てください。 – Matthias

+0

私は問題は、それらを解析する方法、素晴らしいツールだと思う。 – ntziolis

0

を参照してください。

は最近、私はそれは私が私がしたい正確に何をしてみましょうするので、より多くのXMLにLINQを使用し始めている:

var productsXml = XElement.Load(pathXmlFile); 
var products = products.Elements("MyProduct").Select(product 
    select new Product 
    { 
     MyProductCode = (string)product.Attribute("MyProductCode"), 
     MyProductCategory = (string)product.Attribute("MyProductCategory"), 
     MyProductMaxNumber = (int)product.Attribute("MyProductMaxNumber "), 
     MyProductLookups = product.Elements("MyProductLookups") 
      .Elements("MyProductLookup").Select(lookup => 
      { 
       new MyProductLookup() 
       { 
        Lang = (string)lookup.Attribute("Lang"), 
        Value = (string)lookup 
       } 
      } 
    } 

は、だから、IEnumerable<Product>で終わるし、そこからそれを取ることができます。

+0

ありがとう、どうやってXSDツールを使いこなすかを見てみましょう。別のアプローチを調べる必要がある場合は、私はあなたに連絡します。レスポンスに感謝します。 –

関連する問題