Linq To Xml Saving a List Of Nested Objects
I currently load an XML file into a list objects using code like this
XDocument xmlDoc = XDocument.Load(path);
List<ImportDefinition> importDefinitions = xmlDoc.Descendants("Root").Select(xElem => (ImportDefinition)xElem).ToList();
return importDefinitions;
This lis开发者_运维百科t of objects contains nested objects and each one has an operator for parsing the XML into the correct form like this
public static explicit operator Rules(XElement xElem)
{
try
{
return new Rules()
{
FileNameRegEx = (string)xElem.Element("FileNameRegEx"),
FileExtension = (string)xElem.Element("FileExtension")
};
}
catch (Exception ex)
{
return null;
}
This works fine for loading the XML. I now want to save this list of objects back to XML after some edits have been made.
I was hoping something like this would work
XElement xml = new XElement("Root",
from p in ObjectList
select new XElement("File",RootObject
));
}
xml.Save("C:\\temp\\newimport.xml");
However this just seems to output this
<?xml version="1.0" encoding="utf-8"?>
<Root>
<File>MyNamespace.RootObject</File>
<File>MyNamespace.RootObject</File>
</Root>
It looks like its not using the custom operators it uses when loading the files to work out the format to save in. Whats the best way to save this data back to XML to the same format it was in when I read it?
Well for one thing you've only shown us the operator for parsing from an XElement... but even so, you're obviously explicitly calling that in your LINQ expression. If you want the equivalent when building XML, you'll need to be explicit there too:
XElement xml = new XElement("Root",
from p in ObjectList
select new XElement("File", (XElement) p));
Personally I'd use methods instead of operators - ToXElement() and FromXElement() - I think it's clearer that way. ToXElement
would be an instance method; FromXElement
would be a static method. This is a pattern I've used many times, and it's always worked fine.
精彩评论