这种格式的xml配置文件的读取和保存为例。
1,保存
private static string path = Application.dataPath.Replace('\\', '/');
private static string projectPath = path.Substring(0, path.LastIndexOf('/'));
private static string xmlAssetDependencesBundle = outPrintPath + "/" + "AssetDependenceBundles.xml";
public static void SaveAssetsToXml()
{
string xmlPath = xmlAssetDependencesBundle;
XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlRoot = xmlDoc.CreateElement("AssetList");
xmlDoc.AppendChild(xmlRoot);
Dictionary<string, List<string>> orderDic = m_dicAssetDependenceBundle.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
Dictionary<string, List<string>>.Enumerator it = orderDic.GetEnumerator();
while (it.MoveNext())
{
XmlElement xmlAsset = xmlDoc.CreateElement("Asset");
XmlAttribute name = xmlDoc.CreateAttribute("Name");
name.Value = it.Current.Key.ToLower();
xmlAsset.Attributes.Append(name);
XmlAttribute count = xmlDoc.CreateAttribute("Count");
count.Value = (it.Current.Value.Count).ToString();
xmlAsset.Attributes.Append(count);
foreach (string dtPath in it.Current.Value)
{
XmlElement xmlDtAsset = xmlDoc.CreateElement("DtBundle");
XmlAttribute dtName = xmlDoc.CreateAttribute("Name");
dtName.Value = dtPath.ToLower();
xmlDtAsset.Attributes.Append(dtName);
xmlAsset.AppendChild(xmlDtAsset);
}
xmlRoot.AppendChild(xmlAsset);
}
string xmlDir = xmlAssetDependencesBundle.Substring(0, xmlAssetDependencesBundle.LastIndexOf('/'));
if (!Directory.Exists(xmlDir))
Directory.CreateDirectory(xmlDir);
string xmlSavePath = xmlPath + "/" + "AssetDependenceBundles.xml";
xmlDoc.Save(xmlSavePath);
}
2,读取
public static void ReadAssetIncludeBundleXml()
{
xmlAssetDependenceBundle = new Dictionary<string, List<string>>();
XmlDocument xmlDoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
XmlReader xmlReader = XmlReader.Create(xmlAssetDependencesBundle, settings);
xmlDoc.Load(xmlReader);
//Dictionary<string, List<string>> assetDtBundles = new Dictionary<string, List<string>>();
XmlNode rootNode = xmlDoc.SelectSingleNode("AssetList");
XmlNodeList lstNode = rootNode.ChildNodes;
foreach (XmlNode item in lstNode)
{
string assetPath = string.Empty;
List<string> bundles = new List<string>();
XmlElement asset = (XmlElement)item;
assetPath = asset.Attributes["Name"].Value;
XmlNodeList xmlbundles = asset.ChildNodes;
foreach (XmlNode bundle in xmlbundles)
{
bundles.Add(bundle.Attributes["Name"].Value);
}
if (string.IsNullOrEmpty(assetPath) || bundles.Count < 0)
Debug.LogError("资源有问题,资源:" + assetPath);
xmlAssetDependenceBundle.Add(assetPath, bundles);
}
PrintAssetBundleInfoToText(xmlAssetDependenceBundle, readAssetDependenceBundlesXml);
Debug.Log("读取xml成功");
}