tags:

views:

74

answers:

2

For example

<?xml version="1.0" encoding="UTF-8"?>
<!--just example, the actual element structure is rather complex -->
<components>
   <component name='a'/>
   <component name='b'/>
   <component name='c'/>
 </components>

Now I want to create three separate xml file, whose root element is component and the file name is according to the name attribute of them, How can I achieve this?

Regards,

+1  A: 

Using LINQ to XML, something along the lines of

XElement rootElem = ... //load this however you happen to
foreach (var component in rootElem.Elements("component"))
    component.Save(your-XmlWriter-here); //you'll want a distinct writer per file

should work fine; for your specific example...

string xml =@"
    <components>
       <component name='a'/>
       <component name='b'/>
       <component name='c'/>
    </components>
";
foreach (XElement component in XElement.Parse(xml).Elements() )
    component.Save(component.Attribute("name").Value + ".xml");

works exactly as specified. However, I find it to be good practice to avoid dealing with specific file names where possible, since often enough your XML can be processed directly later on in the pipeline without needing an intermediate (error-prone and slow) file save. For example, on a web-server it's not obvious you'll even have permissions to write anything, so you're reducing portability by forcing the usage of an actual file.

Eamon Nerbonne
A: 

Here you go:

System.Xml.XmlDocument daddyDoc = new System.Xml.XmlDocument();
daddyDoc.LoadXml("<?xml version='1.0' encoding='UTF-8'?><components><component name='a'/><component name='b'/><component name='c'/></components>");
foreach (System.Xml.XmlNode sprogNode in daddyDoc.GetElementsByTagName("component"))
{
    System.Xml.XmlDocument sprogDoc = new System.Xml.XmlDocument();
    sprogDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
    sprogDoc.AppendChild(sprogDoc.CreateElement("component"));
    sprogDoc.Save(string.Format("C:\\{0}.xml", sprogNode.Attributes["name"].Value));
}
grenade