2017-09-18 3 views
-2

첫 번째 추가 자식을 추가하고 나중에 노드의 부모를 변경하려고하면 매우 확장 된 XML의 구조를 수정하려고합니다. XML에서 경험이 많지 않으므로 한 개의 자식을 추가 할 수 있었지만 새 부모를 추가하려고 할 때 대체하려는 부모를 모두 제거하는 것처럼 보입니다. 여기C# : 내 XML의 구조를 수정하는 방법?

<root> 
    <products> 
     <product id="1010-1001"> 
      <name> 
      </name> 
      <unit>Styk</unit> 
      <shortDescription /> 
      <longDescription> 
      </longDescription> 
      <currency>DKK</currency> 
      <price> 
      </price> 
      <categories> 
       <category>0912</category> 
      </categories> 
     </product> 
     <product id="1010-1002"> 
      <name> 
      </name> 
      <unit>Styk</unit> 
      <shortDescription /> 
      <longDescription> 
      </longDescription> 
      <currency>DKK</currency> 
      <price>31.982115219</price> 
      <categories> 
       <category>0912</category> 
      </categories> 
     </product> 
    </products> 
</root> 

내가 달성하기 위해 노력하고있어 것 : 여기

는 XML의 전체 구조입니다

<root> 
    <products> 
     <table> 
      <name>BTS pulver 50 g m/antibiotika</name> 
      <Image>.</Image> 
      <longDescription> 
      </longDescription> 
      <product id="1010-1001" /> 
      <shortDescription /> 
      <unit>Styk</unit> 
      <price>10.6600000000000000000000</price> 
     </table> 
    </products> 
</root> 

을 그리고 여기에 내가 함께 넣어 노력 코드입니다 :

XmlNodeList list = doc.SelectNodes("root/products/product"); 




    foreach (XmlNode item in list) 
    { 
     XmlElement Image = doc.CreateElement("Image"); 
     Image.InnerText = "id"; 
     item.AppendChild(Image); 
    } 

    foreach(XmlNode parent in list) 
    { 
     XmlElement table = doc.CreateElement("table"); 
     parent.ParentNode.RemoveChild(parent); 
     table.AppendChild(parent); 
    } 


    doc.Save(Console.Out); 
    Console.ReadKey(); 
+1

https://www.w3schools.com/xml/xsl_intro.asp –

답변

1

"table"요소를 만든 다음이 "table"요소에 기존 항목을 추가합니다. 그러나 문서에 "table"요소를 삽입하지 않으므로 문서가 손실됩니다. products 요소에서 AppendChild (table)을 사용해야합니다.

0

이 같은 LINQ의 XML로 작업을 수행 할 수 있습니다

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

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

      XDocument doc = XDocument.Load(FILENAME); 

      List<XElement> products = doc.Descendants("product").ToList(); 
      foreach (XElement product in products) 
      { 
       product.Add(new XElement("product", new XAttribute("id", (string)product.Attribute("id")))); 

       product.ReplaceWith(new XElement("table", product.Descendants())); 
      } 

     } 
    } 


} 
관련 문제