我试图在xml文件中写一些我迄今为止创建的配置文件非常好,
输入字符串是ProfilesList(0)=“45 65 67”ProfilesList(1)=“profilename”;
public void CreateGroupXML(String GroupNameWithPath, List<String> ProfilesList)
{
ProfilesGroup.ProfilesList = ProfilesList;
XmlWriterSettings ws = new XmlWriterSettings();
ws.NewLineHandling = NewLineHandling.Entitize;
for (int i = 0; i < ProfilesList.Count; i++)
{
ProfilesList[i] += Environment.NewLine;
}
XmlSerializer serializer = new XmlSerializer(typeof(ProfilesGroup));
using (XmlWriter wr = XmlWriter.Create(GroupNameWithPath, ws))
{
serializer.Serialize(wr, ProfilesGroup);
}
}
}
在xml文件中编写的配置文件如下:
ProfilesList="45 65 67
 profilename

到目前为止这么好,问题发生在我尝试从xml文件中读取时,它将第一个配置文件名称拆分为3这里的代码
public List<string> getProfilesOfGroup(string groupNameFullPath)
{
Stream stream = null;
try
{
stream = File.OpenRead(groupNameFullPath);
XmlSerializer serializer = new XmlSerializer(typeof(ProfilesGroup));
_ProfilesGroup = (ProfilesGroup)serializer.Deserialize(stream);
stream.Close();
return _ProfilesGroup.ProfilesList;
}
catch (Exception Ex)
{
log.ErrorFormat("Exception in getProfilesOfGroup: {0}", Ex.Message);
if (stream != null)
{
stream.Close();
}
return null;
}
}
the output (lets call the string ProfileList) contains :
ProfileList(0) = 45
ProfileList(1) = 65
ProfileList(2) = 67
ProfileList(3) = profilename
and i expecting the string to contain
ProfileList(0) = 45 65 67
ProfileList(1) = profilename
在这里编辑完整的xml:
?xml version =“1.0”encoding =“utf-8”?ProfilesGroup xmlns:xsi =“http://www.w3.org/2001/XMLSchema-instance”xmlns:xsd =“http://www.w3 .org / 2001 / XMLSchema“ProfilesList =”45 65 67 profilename“
和 class :
[XmlRootAttribute("VProfilesGroup", IsNullable = false, DataType = "", Namespace = "")]
public class ProfilesGroup
{
[XmlAttribute("ProfilesList")]
public List<String> ProfilesList = new List<string>();
}
1 回答
为什么不删除
[XmlAttribute("ProfilesList")]
属性?您的数据将被成功序列化和反序列化 . XML将如下所示:在这种格式中,字符串列表被明确定义为具有两个条目 . 这是使用
XmlSerializer
序列化和反序列化字符串数组的标准方法 . 或者您是否有一些外部约束使您将列表声明为属性?Update
如果必须将
ProfilesList
序列化为属性而不是元素数组,则可以手动构造和解构字符串,如下所示:生成的XML看起来像:
在这种情况下,我通过序列化和反序列化为字符串而不是文件来测试代码 . 然后帮助者: