C# 使用C从XML创建XML
我有一个XML文件。我正在寻找帮助,以便从这个xml文件创建多个xml文件。新的xml将具有相同EmpID的所有节点-C# 使用C从XML创建XML,c#,xml,xelement,C#,Xml,Xelement,我有一个XML文件。我正在寻找帮助,以便从这个xml文件创建多个xml文件。新的xml将具有相同EmpID的所有节点- <?xml version="1.0" encoding="utf-8"?> <Connected> <Emp> <A.EMPLID>1</A.EMPLID> <A.Phone>12##</A.Phone> </E
<?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>
但它创造了这样的东西:
<?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的所有 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>
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");
}
}
}
}
var empElements = xmlDocument.SelectNodes("//Emp[A.EMPLID=1]");