2012-09-27 3 views
0

linq을 사용하여 이름이 Foo와 같은 MyNode를 찾고 해당 노드의 복사본을 만들어 XML에 추가하려고했지만 새 노드의 이름이 Bar 여야하고 파일을 저장해야합니다.linq을 사용하여 노드를 복사하는 방법은 무엇입니까?

<?xml version="1.0" encoding="utf-8"?> 
<MyRoot> 
    <MyNode Name="Foo"> 
    <Data Type="String">ABC</Data> 
    </MyNode> 
</MyRoot> 

이 코드는 노드를

Dim doc As XDocument = XDocument.Load(xmlFile) 
    Dim sheet = From item In doc...<MyRoot>...<MyNode> Select item Where [email protected] = "Foo" 

을 발견하고 나는 노드를 추가하고 이름을 변경하려면이를 사용하는 것을 시도하고있다.

[email protected] = "Bar" 'After excecuting this, sheet becomes "Nothing" 
    doc.Root.Add(sheet.First) 
    doc.Save(outFile) 

그러나, 설정 시트 후. @ 이름 "바"로, 다음 시트 아무것도된다 없습니다. 그 줄을 주석 처리하면 출력에는 Bar라는 두 노드가 있습니다. 나는

var doc = XDocument.Load(path); 
      var node = doc.Elements("MyRoot").Elements("MyNode").FirstOrDefault(m => m.Attribute("Name").Value == "Foo"); 
      var newNode = new XElement(node); 
      newNode.SetAttributeValue("Name", "Bar"); 
      doc.Root.Add(newNode); 

(번역하려고합니다) 속성을 변경하거나하여 XDocument (또는 둘 다)

답변

1

C# 버전이 추가 약관 중 하나로,이 "올바른 방법"을하고 있지 않다 의심 VB

Dim doc as XDocument = XDocument.Load(xmlFile) 
Dim sheet = From item...<MyNode>.FirstOrDefault(Function(m) [email protected] = "Foo") 
Dim newSheet As New XElement(sheet) 
newSheet.SetAttributeValue("Name", "Bar") 
doc.Root.Add(newSheet) 
0

에 있어야 짐의 대답은 내가 올바른 방향으로 지적되었다. 여기에 나온 코드는

Dim doc As XDocument = XDocument.Load(xmlFile) 
    Dim sheet = From item In doc...<MyRoot>...<MyNode> Select item Where [email protected] = "Foo" 
    Dim copy As XElement = New XElement(sheet.First) 
    copy.SetAttributeValue("Name", "Bar") 
    doc.Root.Add(copy) 
    doc.Save(outFile) 
관련 문제