簡體   English   中英

使用C#從xml創建XML

[英]Create XMLs from xmls using C#

我有一個XML文件。 我正在尋找從該xml文件創建多個xml文件的幫助。 新的xml將具有具有相同EmpID的所有節點。我正在使用C#代碼,並且能夠創建xml的Xml看起來像這樣-

<?xml version="1.0" encoding="utf-8"?>
      <Connected>
      <Emp>
          <A.EMPLID>1</A.EMPLID>
          <A.Phone>12##</A.Phone>
      </Emp>
      <Emp>
          <A.EMPLID>1</A.EMPLID>
          <A.Add>XXXXXXX</A.Add>
      </Emp>
      <Emp>
          <A.EMPLID>2</A.EMPLID>
         <A.Phone>##34</A.Phone>
      </Emp>
      <Emp>
         <A.EMPLID>3</A.EMPLID>
      </Emp>
      <Emp>
         <A.EMPLID>3</A.EMPLID>
         <A.Add>XXXXXXX</A.Add>
     </Emp>
    </Connected>

輸出將是3種不同的EmplId的3種不同的Xml

1.XML

 <Connected>
     <Emp>
      <A.EMPLID>1</A.EMPLID>
      <A.Phone>12##</A.Phone>
     </Emp>
    <Emp>
      <A.EMPLID>1</A.EMPLID>
      <A.Add>XXXXXXX</A.Add>
    </Emp>
</Connected>

2.XML

  <Connected>
      <Emp>
      <A.EMPLID>2</A.EMPLID>
      <A.Phone>##34</A.Phone>
      </Emp>
  </Connected>

3.XML

 <Connected>
     <Emp>
         <A.EMPLID>3</A.EMPLID>
     </Emp>
     <Emp>
         <A.EMPLID>3</A.EMPLID>
         <A.Add>XXXXXXX</A.Add>
     </Emp>
 </Connected>

我正在嘗試執行該C#代碼。 使用XElement

      XElement x = new XElement("Connected",new XElement("Emp",new XElement("A.EMPLID", group.Key),group.Select(g => g.Elements().Where(e =>e.Name != "A.EMPLID"))));

但是它正在創建這樣的東西:

<?xml version="1.0" encoding="utf-8"?>
<Connected>
<Emp>


<A.EMPLID>1</A.EMPLID>


<A.Phone>12##</A.Phone>


<A.Add>XXXXXXX</A.Add>


</Emp>


</Connected>   

我需要將為Empld生成的3個xml,但是節點的順序應完全相同。

使用xml linq:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string ident = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Connected></Connected>";

            XDocument doc = XDocument.Load(FILENAME);

            var groups = doc.Descendants("Emp").GroupBy(x => (string)x.Element("A.EMPLID")).ToList();
            foreach (var group in groups)
            {
                XDocument doc1 = XDocument.Parse(ident);
                XElement root = doc1.Root;

                root.Add(group);

                doc1.Save(@"c:\temp\test" + group.Key + ".xml");
            }

        }
    }
}

實現此目標的另一種方法是使用XPath。

var empElements = xmlDocument.SelectNodes("//Emp[A.EMPLID=1]");

上面的查詢將返回屬於特定ID(在本例中為1)的所有<Emp>節點。

暫無
暫無

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

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