应用程序应不时将节点添加到Goals.xml
文件。所以dynamic
。添加节点的代码:
XmlWriterSettings settings=new XmlWriterSettings();
settings.OmitXmlDeclaration= true;
settings.Indent = true;
settings.IndentChars = ("\t");
using (IsolatedStorageFile myIsolatedStorage =
IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream stream =
myIsolatedStorage.OpenFile("Goals.xml", FileMode.Append))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Goals>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
{
serializer.Serialize(
xmlWriter,
GenerateGoalsData(name, description, progress));
}
}
和
private List<Goals> GenerateGoalsData(
string name,
string description,
string progress)
{
List<Goals> data = new List<Goals>();
data.Add(new Goals() {
Name=name,
Description=description,
Progress=progress});
return data;
}
我还有班级Goals
。但它会产生错误的XML
:
<ArrayOfGoals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Goals>
<Name>Jack</Name>
<Description>lalala</Description>
<Progress>97</Progress>
</Goals>
</ArrayOfGoals>
<ArrayOfGoals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Goals>
<Name>Taaaaaa</Name>
<Description>nanana</Description>
<Progress>50</Progress>
</Goals>
</ArrayOfGoals>
如何删除重复的XML
:
</ArrayOfGoals>
<ArrayOfGoals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
所以XML
看起来像那样:
<ArrayOfGoals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Goals>
<Name>Jack</Name>
<Description>lalala</Description>
<Progress>97</Progress>
</Goals>
<Goals>
<Name>Taaaaaa</Name>
<Description>nanana</Description>
<Progress>50</Progress>
</Goals>
</ArrayOfGoals>
或者如何在没有自动添加该字符串的情况下附加节点?
答案 0 :(得分:2)
反序列化数据,添加新值并序列化。但
使用FileMode.Create
代替FileMode.Append
答案 1 :(得分:2)
生成的文件是无效的XML,因此您无法将其直接用于反序列化为有效的Xml。
但它实际上是有效的“Xml片段”,可以用标准类读取:XmlReader可以在XmlReader.Create调用的XmlReaderSettings中指定ConformanceLevel.Frament时读取片段。我想你甚至可以直接从这样的读者反序列化类(不确定)。
旁注:阅读旧数据会更容易(但问题和错误更少),附加您需要的内容并序列化为整个文件。
答案 2 :(得分:0)
XmlRootAttribute root = new XmlRootAttribute("Goals");
XmlSerializer serializer = new XmlSerializer(typeof(List<Goals>), root);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
{
serializer.Serialize(xmlWriter, GenerateGoalsData(name, description, progress), ns)
}