2012-02-09 9 views
0

最近、XML構造を平坦化するためのポストを作成したので、すべての要素とその値はルート要素の属性に変換されました。いくつかの素晴らしい答えを得て、それを働かせました。しかし、悲しいこと平坦化することにより、クライアントは属性にそれらを構成する要素を平らにしていないためのものということである: - 私が持っているもの/linqからxmlへの要素によるXML構造の統合

はこれです:

<members> 
    <member xmlns="mynamespace" id="1" status="1"> 
     <sensitiveData> 
      <notes/> 
      <url>someurl</url> 
      <altUrl/> 
      <date1>somedate</date1> 
      <date2>someotherdate</date2> 
      <description>some description</description> 
      <tags/> 
      <category>some category</category> 
     </sensitiveData> 
     <contacts> 
      <contact contactId="1"> 
       <contactPerson>some contact person</contactPerson> 
       <phone/> 
       <mobile>mobile number</mobile> 
       <email>[email protected]</email> 
      </contact> 
     </kontakter> 
    </member> 
</members> 

そして、何私は必要は以下の通りです。

<members> 
    <member xmlns="mynamespace" id="1" status="1"> 
     <sensitiveData/> 
     <notes/> 
     <url>someurl</url> 
     <altUrl/> 
     <date1>somedate</date1> 
     <date2>someotherdate</date2> 
     <description>some description</description> 
     <tags/> 
     <category>some category</category> 
     <contacts/> 
     <contact contactId="1"></contact> 
     <contactPerson>some contact person</contactPerson> 
     <phone/> 
     <mobile>mobile number</mobile> 
     <email>[email protected]</email> 
    </member> 
</members> 

したがって、基本的にすべての要素が、子ノードとしてフラット化されます。私はこのようなXML文書の解析を始めるのはきわめて簡単ではないことを知っていますが、データをインポートするCMSはこのフラットな構造を必要とし、XML文書は外部Webサービスから来ているため、

私はこれに対して再帰的メソッドを作成し始めましたが、LINQ to XML(?)ではよりスムーズに(できるだけスムーズに)することができるという奇妙な感覚を持っています。 linqからxmlへのベストなので、誰かがこの問題を解決するヒントを与えるのに役立つだろうと思っていますか? :-)

ご協力いただきありがとうございます。

ありがとうございます。

/ボー

答えて

2

これは動作するようです - 確かにすっきりアプローチがあるかもしれません。確かに動作します

var doc = XDocument.Load("test.xml"); 
XNamespace ns = "mynamespace"; 
var member = doc.Root.Element(ns + "member"); 

// This will *sort* of flatten, but create copies... 
var descendants = member.Descendants().ToList(); 

// So we need to strip child elements from everywhere... 
// (but only elements, not text nodes). The ToList() call 
// materializes the query, so we're not removing while we're iterating. 
foreach (var nested in descendants.Elements().ToList()) 
{ 
    nested.Remove(); 
} 
member.ReplaceNodes(descendants); 
+0

こんにちはジョン、!どうもありがとうございました:)私が理解できない唯一のことは、要素の属性を保持する方法です(私と一緒にいて、私はXML構文解析に関して最も鋭いナイフではありません)。それらは要素のコピーを作成するときに削除されるようですか? :) – bomortensen

+0

@bomortensen:彼らはこの場合削除されていないようです - 私はまだcontactId = "1"を持っています...おっと、私は気がついたのは、要素そのもの。それを修正するつもりです。 –

+0

@bomortensen:うん、固定しました - 最後の行はReplaceAllではなくReplaceNodesになりました –

関連する問題