2016-09-13 8 views
0

xml과 관련하여 XDocument 가능성에 대해 궁금하고 xml을 어떻게 수정할 수 있는지 궁금합니다. 이 전 다음 XML을 가정 해 봅시다 :XDocument/XPath를 사용하여 XML 수정 C#

<client> 
     <firstName>Ian</firstName> 
     <firstName>Charles</firstName> 
     <city>LosAngeles</city> 
     <state>California</state> 
    </client> 

내가하여 XDocument 또는 XPath는 작업을 사용하여가 (매우 상단에) 하나의 "FIRSTNAME"노드를 떠날 수 있습니까? LINQ에서 .Distinct() 연산과 같은 작업을 수행하려고합니다. 나는 내 결과 XML은 다음과 같이 만들고 싶어 :

<client> 
     <firstName>Ian</firstName> 
     <city>LosAngeles</city> 
     <state>California</state> 
    </client> 
+0

이 어떤 소용이겠습니까? http://stackoverflow.com/questions/1987470/xpath-to-get-unique-element-names –

+0

첫 번째 이름 태그는 항상 원하는 태그입니까? –

+0

예, firstname 태그는 항상 내가 원하는 태그입니다. – Bill

답변

2

는 그냥 client 내의 모든 firstName 요소를 검색하고 첫번째를 제외한 나머지를 모두 제거합니다. 이 XPath 쿼리를 사용하여 제거 할 수 firstName 모든 요소를 ​​찾을 수 있습니다

//client/firstName[position() > 1] 

그래서 단지 그들을 제거합니다.

doc.XPathSelectElements("//client/firstName[position() > 1]").Remove(); 
1

의 XML LINQ를 사용 :

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

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Load(FILENAME); 

      foreach(XElement client in doc.Descendants("client")) 
      { 
       List<XElement> firstNames = client.Elements("firstName").ToList(); 
       XElement newFirstName = new XElement(firstNames.FirstOrDefault()); 
       firstNames.Remove(); 
       client.AddFirst(newFirstName); 
      } 
     } 
    } 
}