UNITY 3D C# XML MERGE
本文关键字:MERGE XML 3D UNITY | 更新日期: 2023-09-27 18:04:14
合并两个XML文件并创建新文件的最简单方法是什么?我正在使用unity,我认为它在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>
我将首先使您的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,它做得很好!
保存和加载数据,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);