2012-11-20 4 views
1

XContainer를 사용하여 루트 요소를 포함하여 내용을 완전히 포장하고 싶습니다. XContainer에는 XML이 포함되어 있습니다. 부모 요소에 XContainer 내용을 래핑하여 XHTML 문서를 만들려고합니다.루트 요소를 포함하여 XContainer의 요소를 바꿉니다.

XElement headElement = new XElement("head"); 
XElement bodyElement = new XElement("body", container); 
container.ReplaceWith(new XElement("html", headElement, bodyElement)); 

위의 코드는 작동하지 않습니다. 이것이 가능한가? 아니면 다른 XContainer를 만들고 원래 XContainer의 내용으로 빌드해야합니까? 막연한 질문에 대한

업데이트

죄송합니다. 일부 상황을 추가하겠습니다. 나는 XContainer를 인수로 취하는 메소드를 가지고있다. 이 XContainer 인스턴스를 수정하고 싶습니다. 원하는 최종 결과는 본래의 XContainer 내용이 본문 요소에서 "감싸 인"것입니다. 아래 예제에서 ReplaceWith() 호출 후 XContainer는 변경되지 않은 것 같습니다. 컨테이너가 엘레 메넷 "html, head, or body"를 포함하지 않는다는 것을 의미합니다. 희망이 더 분명하다.

protected void BuildXhtmlDocument(XContainer container) 
    { 
     XElement headElement = new XElement("head"); 
     XElement bodyElement = new XElement("body", container); 
     container.ReplaceWith(new XElement("html", headElement, bodyElement)); 
    } 

답변

0

나를 위해 일합니다. 예를 들면 :

using System; 
using System.Xml.Linq; 

public class Test 
{ 
    static void Main() 
    { 
     XDocument doc = new XDocument(); 
     doc.Add(new XElement("foo", new XElement("bar"))); 
     Console.WriteLine("Before:"); 
     Console.WriteLine(doc); 
     Console.WriteLine(); 

     XContainer container = doc.Root; 
     XElement headElement = new XElement("head"); 
     XElement bodyElement = new XElement("body", container); 
     container.ReplaceWith(new XElement("html", headElement, bodyElement)); 
     Console.WriteLine("After:"); 
     Console.WriteLine(doc); 
    } 
} 

출력 : 그것은 완벽하게 행동하는 것처럼

Before: 
<foo> 
    <bar /> 
</foo> 

After: 
<html> 
    <head /> 
    <body> 
    <foo> 
     <bar /> 
    </foo> 
    </body> 
</html> 

보인다. (이 은 문서의 루트 요소로이 발생하지만 반드시 그럴 필요는 없습니다.)

이제 실제로 도움이 될 수 있도록, 위의 작업을 다시 시도해보십시오. 또는 일 경우 코드와 사용자 코드의 차이를 확인해야합니다.

+0

내 질문이 업데이트되었습니다. 내가 시도하고있는 것이 더 분명해지기를 바랍니다. 응답 해 주셔서 감사합니다. – Nick

관련 문제