我正在尝试阅读这个xml:
<player>
<id>10101</id>
<name>Ricardo Ferreira Rodrigues</name>
<shirtnumber>1</shirtnumber>
<position>Guarda Redes</position>
<realteam>5</realteam>
</player>
我有这段代码:
private async void LoadXml()
{
try
{
StorageFolder storageFolder = Package.Current.InstalledLocation;
StorageFile storageFile = await storageFolder.GetFileAsync("/users/1101046102/xml/players.xml");
string xml = await FileIO.ReadTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);
var doc = XDocument.Parse(xml);
txtnome.Text = (string)doc.Root.Element("name");
txtshirtnumber.Text = (string)doc.Root.Element("shirtnumber");
txtposition.Text = (string)doc.Root.Element("position");
}
catch (Exception ex)
{
XmlTextBlock.Text = ex.Message;
}
}
我得到的这个“价值不在预期的范围异常范围内”。有人可以告诉我为什么?
答案 0 :(得分:1)
您的XML文档有两个根元素,都是“播放器”类型。
您的代码正在尝试将其加载到XDocument中,因此存在问题。
尝试将xml元素包装在容器节点中,如此...
<players>
<player /> <!-- copied from above -->
<player /> <!-- copied from above -->
</players>
然后,您需要重写查询以查看根元素的子节点。请注意,由于您有多个它们,您应该尝试将它们读入集合。
string xml = "<players>"
+ " <player>"
+ " <id>10101</id>"
+ " <name>Ricardo Ferreira Rodrigues</name>"
+ " <shirtnumber>1</shirtnumber>"
+ " <position>Guarda Redes</position>"
+ " <realteam>5</realteam>"
+ " </player>"
+ " <player>"
+ " <id>10103</id>"
+ " <name>Antonio Manuel</name>"
+ " <shirtnumber>2</shirtnumber>"
+ " <position>Defesa</position>"
+ " <realteam>5</realteam>"
+ " </player>"
+ "</players>";
var doc = XDocument.Parse(xml);
var rootNode = doc.Root;
foreach (var child in rootNode.Descendants("player"))
{
// do something with the values of the child nodes here.
}
请注意,在循环中将这些值分配给您拥有的文本控件是没有意义的,因为只有集合中的最后一个将以用户可以使用的方式写出来。
答案 1 :(得分:-1)
我想要的xml是:
<player>
<id>10101</id>
<name>Ricardo Ferreira Rodrigues</name>
<shirtnumber>1</shirtnumber>
<position>Guarda Redes</position>
<realteam>5</realteam>
</player>
<player>
<id>10103</id>
<name>Antonio Manuel</name>
<shirtnumber>2</shirtnumber>
<position>Defesa</position>
<realteam>5</realteam>
</player>
使用此xml我得到错误“值不在预期的范围异常范围内”。
<TextBlock Name="txtnome" HorizontalAlignment="Left" Margin="178,275,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<TextBlock Name="txtshirtnumber" HorizontalAlignment="Left" Margin="178,300,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<TextBlock Name="XmlTextBlock" HorizontalAlignment="Left" Margin="178,250,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<TextBlock Name="txtposition" HorizontalAlignment="Left" Margin="178,325,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
这是我的文本块