2009-10-29 6 views
5

XDocument가 있고 노드를 제거하고 일부 조작 후에 다시 동일한 노드를 다시 추가해야합니다 (내 xelement 노드는 복잡하고 내부 노드가 잘). xmldocument 맨 끝에 새로운 조작 된 노드가 추가 될 때 누구나이 작업을 수행 할 수있는 좋은 방법이 있습니다. 모든 코드 스 니펫은 크게 감사하겠습니다.Linq to XML - 노드를 제거하고 같은 위치에 새 노드를 추가합니다.

답변

4

방금 ​​노드를 편집하는 경우, 왜 모두를 제거? 트리에서 트리에 대한 참조를 가져 와서 현재 위치에서 편집하십시오.

그 어떤 이유에 대한 옵션이 아니라면, 다음에 대해 갈 수있는 한 가지 방법이 있습니다 : 당신은이 XElement (또는, 일반적으로, XNode)를 사용하면 트리에서 교체해야, 새로운 XElement 만들 찾았 으면 대체품으로 사용하려면 이전 요소에서 XNode.ReplaceWith 메서드를 사용하고 새 요소를 인수로 전달하십시오.

8

내가 이해한다면, 도움이 될 것입니다.

SolarSystem.xml :

<?xml version="1.0" encoding="UTF-8"?> 
<SolarSystem> 
    <Planets> 
    <Planet Id="1"> 
     <Name>Mercury</Name> 
    </Planet> 
    <Planet Id="2"> 
     <Name>Venus</Name> 
    </Planet> 
    <Planet Id="3"> 
     <Name>Earth</Name> 
    </Planet> 
    </Planets> 
</SolarSystem> 

코드가 <Planet> 수성 발견은, 그것을 제거, 거기에 추가 요소를 추가하고, <Planets> 수집의 끝에서 다시 삽입. 제공

XDocument SolarSystem = XDocument.Load(Server.MapPath("SolarSystem.xml")); 
IEnumerable<XElement> Planets = SolarSystem.Element("SolarSystem").Element("Planets").Elements("Planet"); 

// identify and change Mercury 
XElement Mercury = Planets.Where(p => p.Attribute("Id").Value == "1").FirstOrDefault(); 
Mercury.Add(new XElement("YearLengthInDays", "88")); 

// remove Mercury from current position, and add back in at the end 
Mercury.Remove(); 
Planets.Last().AddAfterSelf(Mercury); 

// save it as new file 
SolarSystem.Save(Server.MapPath("NewSolarSystem.xml")); 

:

<?xml version="1.0" encoding="UTF-8"?> 
    <SolarSystem> 
    <Planets> 
     <Planet Id="2"> 
     <Name>Venus</Name> 
     </Planet> 
     <Planet Id="3"> 
     <Name>Earth</Name> 
     </Planet> 
     <Planet Id="1"> 
     <Name>Mercury</Name> 
     <YearLengthInDays>88</YearLengthInDays> 
     </Planet> 
    </Planets> 
    </SolarSystem> 
+1

+1 : 시작하기 좋은 101 샘플 –

1

위의 @Ralph Lavelle의 예제를 바탕으로 작성되었습니다. 나는 완전한 콘솔 앱을 만들었고, 코드 &을 더 잘 이해할 수 있었다. 내가 그것을 공유 할 것이라고 상상했다. 위와 똑같은 예제 XML을 사용하지만 Server.MapPath()에 대한 참조를 제거해야만했습니다. 여기에 당신이 간다 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Xml.Linq; 

class LinqDemo 
{ 
static void Main() 
    { 
     XDocument SolarSystem = XDocument.Load("SolarSystem.xml"); 
     IEnumerable<XElement> Planets = SolarSystem.Element("SolarSystem").Element("Planets").Elements("Planet"); 

     // identify and change Mercury 
     XElement Mercury = Planets.Where(p => p.Attribute("Id").Value == "1").FirstOrDefault(); 
     Mercury.Add(new XElement("YearLengthInDays", "88")); 

     // remove Mercury from current position, and add back in at the end 
     Mercury.Remove(); 
     Planets.Last().AddAfterSelf(Mercury); 

     // save it as new file 
     SolarSystem.Save("NewSolarSystem.xml"); 
    } 
} 

어쩌면이 같은 또 다른 LINQ noob 도움이됩니다.

+0

간결한 작업 예제를 이해합니다. 'using system;'이 (가) ***이 아닌 것으로 밝혀졌습니다. 하지만 그 using System.Xml; *** *** 필요합니다. – DavidRR

+0

대단히 환영합니다. 내가 찾고있는 대답을 가지고있는 것처럼 보이는 질문을 찾는 것과 실제적으로 그것에 대해가는 모호한 코드는 싫다. 사용 오류를 잘 잡으십시오. – delliottg

관련 문제