C#:填充XML文件

问题描述 投票:0回答:1

因此,我已经有一个XML文件,其中包含很多Elements,但是其中没有任何值。现在,我想在该现有XML文件中插入一些值。因此,我创建了一个XmlWriter和一个XmlReader。之后,我开始编写XMLDocument并像这样从Reader复制所有内容:

xmlWriter.WriteStartDocument();
xmlWriter.WriteNode(reader, true);

如果我就这样保留它(当然是xmlWriter.WriteEndDocument();xmlWriter.Close();最后,那么我将拥有一个新的XML文件,它是我的默认文件的完全副本。

我的问题是:是否可以添加一些值,然后保护此新XML文件安全?因此基本上是默认值+值的副本。

如果您想知道,我的意思是值,我的意思是“ TestUser”,如下所示:

<User>TestUser</User>

我已经在Internet上做了一些研究如何做到这一点,但可惜我找不到任何东西。

感谢您的帮助!

编辑:

我的XML看起来像这样(当然更大,那只是一个小例子):

<users>
    <user></user>
    <user></user>
</users>

而且我希望将此XML与某些附加值一起复制,例如:

<users>
    <user>TestUser1</user>
    <user>TestUser2</user>
</users>
c# xml xmlreader xmlwriter
1个回答
-1
投票

因此您可以在此处使用此类,并打开使用对象时需要记住的XML,并使用不同的路径保存新文件,或者只是在_Serialize(string filePath,T object)中重命名该文件

    public static StreamReader _StreamReader(string filePath)
    {
        try
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new InvalidOperationException();
            }

            return new StreamReader(filePath);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static void _Serialize<T>(string filePath, T object)
    {
        try
        {
            var xmlSerializer = new XmlSerializer(object.GetType());
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            {
                xmlSerializer.Serialize(fileStream, object);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static T _UnSerialize<T>(StreamReader streamReader)
    {
        try
        {
            T deserializedObject = default(T);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            deserializedObject = (T)xmlSerializer.Deserialize(streamReader);
            streamReader.Dispose();
            return deserializedObject;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.