簡體   English   中英

棘手的 XML 操作:根據自己和其他兄弟的數據創建一個元素

[英]Tricky XML Manipulation: Create an element out of its own and other sibling's data

我有這個復制場景我的 XML 文檔如下:

<?xml version="1.0" encoding="utf-8"?>
<Home>
   <Kitchen>
      <Pantry>
         <Ingredients>
            <Name>Tomato</Name>
            <ID>1</Price_ID>
            <Name>Tomato</Name>
            <Income>Sales</Income>  // replace the <Income> element with its value <Sales>
            <Cost>Materials</Cost>
            <Price>100</Price>      // the value for new <Sales> element shall be this <Price> value
          </Ingredients>
          //.. and thousands more sets of ingredients
       </Pantry>
    </Kitchen>
</Home>
//.. and thousands more sets of ingredients

我想以以下方式對其進行重組:

<?xml version="1.0" encoding="utf-8"?>
<Home>
   <Kitchen>
      <Pantry>
         <Ingredients>
            <Name>Tomato</Name>
            <ID>1</ID>
            <Name>Tomato</Name>
            <Sales>100</Sales>      // the <Income> was replaced by its value and the value was taken from the <Price> element that was deleted also
            <Cost>Materials</Cost>           
          </Ingredients>
          //.. and thousands more sets of ingredients
       </Pantry>
    </Kitchen>
</Home>

我仍在試圖弄清楚我將如何做到這一點。 我會很感激這里的任何幫助。

使用 Xml 玲:

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

namespace ConsoleApplication37
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> ingredients = doc.Descendants("Ingredients").ToList();

            foreach (XElement ingredient in ingredients)
            {

                XElement xIncome = ingredient.Element("Income");
                XElement xPrice = ingredient.Element("Price");
                xIncome.ReplaceWith(new XElement("Sales", (string)xPrice));
                xPrice.Remove();
            }
           
        }
    }
}

首先為新的 Model 創建一個Class

public class NewIngredients 
{
   public int Id { get; set; }
   public string Name { get; set; }
   public decimal Sales { get; set; }
   public string Cost{ get; set; }
}

假設 Xml 文檔位於名為Kitchen.xml的文件中

XElement Kitchen = XElement.Load(@"Kitchen.xml");

然后使用Linq to Xml Xml 從舊的類似的東西創建新的 model (注意可能需要檢查空值等)

var newIngredients = Kitchen.Descendants("Ingredients").Select(x => new NewIngredients
{
  Id = int.Parse(x.Element("ID").Value),
  Name = x.Element("Name").Value,
  Sales = decimal.Parse(x.Element("Price").Value)
  Cost = x.Element("Cost").Value
});

如果需要,轉換回 xml

var serializer = new XmlSerializer(newIngredients.First().GetType());
serializer.Serialize(Console.Out, newIngredients.First()); //Printed to console but could move to file if needed

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM