2012-02-09 4 views
0

최근에 XML 구조를 병합하는 게시글을 만들었습니다. 모든 요소와 값은 루트 요소의 특성으로 바뀌 었습니다. 훌륭한 대답을 얻었고 작동하도록했습니다. 그러나, 슬픈 일이 병합에 의해, 클라이언트는 속성으로 그들을 구성하는 요소를 평평하지 의미이다 : -/linq to 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 문서가 외부 웹 서비스에서 제공되기 때문에 남은 유일한 옵션입니다.

나는 이것을 재귀 적 방법으로 만들었지 만, 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"인 경우 ... Ooh, 'member'속성을 제거한 것으로 나타났습니다. 요소 자체. 그걸 고칠거야, 기다려. –

+0

@bomortensen : 예, 고정되었습니다. 마지막 줄은 ReplaceAll이 아닌 ReplaceNodes입니다. –

관련 문제