简体   繁体   English

Linq To Xml保存嵌套对象列表

[英]Linq To Xml Saving a List Of Nested Objects

I currently load an XML file into a list objects using code like this 我目前使用这样的代码将XML文件加载到列表对象中

    XDocument xmlDoc = XDocument.Load(path);
    List<ImportDefinition> importDefinitions = xmlDoc.Descendants("Root").Select(xElem => (ImportDefinition)xElem).ToList();
    return importDefinitions;

This list of objects contains nested objects and each one has an operator for parsing the XML into the correct form like this 这个对象列表包含嵌套的对象,每个对象都有一个运算符,用于将XML解析为正确的格式,如下所示

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. 这对于加载XML很好。 I now want to save this list of objects back to XML after some edits have been made. 现在,在进行了一些编辑之后,我现在希望将此对象列表保存回XML。

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? 看起来好像它没有使用加载文件时要使用的自定义运算符来计算要保存的格式。将数据保存回XML的最佳方法是什么?

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. 好吧,您只向我们展示了用于 XElement进行解析的运算符...但是,即使如此,您显然仍在LINQ表达式中显调用了该运算符。 If you want the equivalent when building XML, you'll need to be explicit there too: 如果在构建XML时需要等效的方法,则也需要在其中明确说明:

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()和FromXElement()-我认为这样更清晰。 ToXElement would be an instance method; ToXElement将是一个实例方法; FromXElement would be a static method. FromXElement将是一个静态方法。 This is a pattern I've used many times, and it's always worked fine. 这是我使用过很多次的模式,并且始终运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM