UNITY 3D C#XML MERGE

时间:2016-08-26 13:43:35

标签: c# xml

合并两个XML文件并创建新文件的最简单方法是什么?我使用统一性,我认为它在C#API和参考文献中是有限的,而且我不是专业程序员。

文件1:

<?xml version="1.0" encoding="UTF-8"?>
<UserData>

  <Data>

  <FIELD1>NAME 1</FIELD1>

  </Data>

</UserData>

文件2:

<?xml version="1.0" encoding="UTF-8"?>
<UserData>


  <Data>

  <FIELD2>NAME 2</FIELD2>

  </Data>

</UserData>

结果:

<?xml version="1.0" encoding="UTF-8"?>
 <UserData>

  <Data>

   <FIELD1>NAME 1</FIELD1>      
   <FIELD2>NAME 2</FIELD2>

  </Data>

 </UserData>

1 个答案:

答案 0 :(得分:0)

我首先要使UserData的实现更通用,以便它可以接受多个字段类型而不是field1和field2,例如:

<?xml version="1.0" encoding="UTF-8"?>
<UserData>
  <Data>
    <Field>NAME 1</Field>      
    <Field>NAME 2</Field>
  </Data>
</UserData>

您的容器可能如下所示:

[XmlRoot("UserData")]
public class UserDataContainer
{
    public UserDataContainer() {...}
    // Can be used load and save a list of strings (Field(s) in XML)
    [XmlArray("Data"), XmlArrayItem("Field"),Type = typeof(string))]
    public List<string> Data = new List<string>();

    public static UserDataContainer Load(path){...}

    public void Save(path){...}

    public List<string> GetFields(){...}

    public void SetFields(List<string> Fields){...}
}

如果您需要有关加载/编写数据的帮助,可以查看这个wiki,它做得非常好!

Saving and Loading Data, XmlSerializer

您可以加载两个UserData文件,如:

UserDataContainer UserData1 = UserDataContainer.Load(UserData1Path);
UserDataContainer UserData2 = UserDataContainer.Load(UserData2Path);

稍后当你想要合并它们时,你可以这样做:

// Get the contents of the first user data
List<string> CombinedDatas = UserData1.GetFields();

// Combine in the contents of the second user data
// AddRange actually changes the first list (CombinedDatas)
CombinedDatas.AddRange(UserData2.GetFields());

// If you wanted to save out the combined data in a new xml file
UserDataContainer FinalData = new UserDataContainer();
FinalData.SetFields(CombinedDatas);

FinalData.Save(FinalDataPath);