您好我使用此代码保存xml文件
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("test.xml", FileMode.Create, myIsolatedStorage))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
{
writer.WriteStartElement("t", "test", "urn:test");
writer.WriteStartElement("TestA", "");
writer.WriteString(lbTestA.Text);
writer.WriteEndElement();
writer.WriteStartElement("TestB", "");
writer.WriteString(lbTestB.Text);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
}
}
它创建了使用Isolated Storage Explorer for WP7检查的正确xml文件,现在我想只读取存储在和标签中的值,我可以使用的唯一代码就是这个
private void loadgame_Click(object sender, EventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("test.xml", FileMode.Open);
using (StreamReader reader = new StreamReader(isoFileStream))
{
lsScore.DataContext = reader.ReadToEnd();
}
}
}
但它只是读取整个xml文件,因为它只是一个文本,任何想法?
答案 0 :(得分:0)
reader.ReadToEnd()将整个文件读取为字符串。如果你想要它作为XML,你必须构造一个XDocument,例如:
var doc = XDocument.Parse(reader.ReadToEnd());
然后使用LINQ从XML文档中获取所需的内容。
答案 1 :(得分:0)
读取xml文件的代码。我在值之间使用了一个分隔符,后来使用.Split来分隔值
private void loadtest_Click(object sender, EventArgs e)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
if (storage.FileExists("test.xml"))
{
IsolatedStorageFileStream fileStream = storage.OpenFile("test.xml", FileMode.Open, FileAccess.ReadWrite);
XDocument test = XDocument.Load(fileStream);
string score = test.Root.Value.ToString();
string[] scores = score.Split(',');
foreach (string s in scores)
{
lbTestAScore.Text= scores[0].ToString();
lbTestBScore.Text = scores[1].ToString();
}
XML文件
<?xml version="1.0" encoding="utf-8"?>
<test>
<TeamA>300</TeamA>
<Seperator>,</Seperator>
<TeamB>-200</TeamB>
</test>
字符串score = test.Root.Value.ToString();
是300,-200
我认为这总结了一切。