0

我正在处理许多大型描述性 XML 文件,我只需要读取最外层的元素、更改值然后再次将其保存。

举个例子 -

<Model Name="someModel">
    <Material Name="someMaterial" Effect="someEffect">
        <Texture Name="tex1" Path="somePath"/>
        <Colour Name="colour1" Value="FFF"/>
        <Layer Index="0"/>
        ... many more elements I don't are about
    </Material>
</Model>

我想反序列化上述内容,更改 Material 属性,然后再次将其保存回来。但由于我不关心材料元素(只是它的属性),我宁愿不必将它们全部添加到我反序列化的类中,.. 但是,当我保存时,我仍然需要将它们写回。

目前,我正在这样做,但我想知道是否有更好的方法。

namespace WpfApplication9
{
    public class Material
    {
        [XmlAttribute]
        public string Name
        {
            get;
            set;
        }

        [XmlAttribute]
        public string Effect
        {
            get;
            set;
        }
    }

    public class Item
    {
        [XmlAttribute]
        public string Name
        {
            get;
            set;
        }

        public Material Material
        {
            get;
            set;
        }

        public static Item Load(string _path)
        {
            Item item = new Item();
            item.m_doc = new XmlDocument();
            item.m_doc.Load(_path);

            XmlNode rootNode = item.m_doc.FirstChild;

            item.Name = rootNode.Attributes["Name"].InnerText;

            XmlNode materialNode = rootNode.FirstChild;

            item.Material = new Material();
            item.Material.Name = materialNode.Attributes["Name"].InnerText;
            item.Material.Effect = materialNode.Attributes["Effect"].InnerText;

            return item;
        }

        public void Save(string _path)
        {
            XmlNode rootNode = m_doc.FirstChild;

            rootNode.Attributes["Name"].InnerText = Name;

            XmlNode materialNode = rootNode.FirstChild;

            materialNode.Attributes["Name"].InnerText = Material.Name;
            materialNode.Attributes["Effect"].InnerText = Material.Effect;

            m_doc.Save(XmlWriter.Create(_path, new XmlWriterSettings()
            {
                IndentChars = "\t",
                Indent = true
            }));
        }

        XmlDocument m_doc;
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Item item = Item.Load("Data.xml");
            item.Name = "Terry";
            item.Save("Data.xml");
        }
    }
}
4

1 回答 1

0

There is the XmlAnyElementAttribute. It instructs the deserializer to store unrecognized elements as is. However, depending on your case you might be better served using an XmlReader-XmlWriter filter, or an XmlDocument with XPath.

于 2013-01-30T00:23:08.623 回答