从C#中的xml文件读取值时出现System.InvalidOperationException

时间:2017-07-05 11:42:27

标签: c# xml

所以我有这个代码示例......它应该做的是......从xml文件中读取一个值......

    XDocument xdoc = XDocument.Load(FileLoc);
    MessageBox.Show(xdoc.Descendants("energyPieces").First().Value);

但是在第二行我总是得到System.InvalidOperationException ...当xml文件有效时:我用游戏检查它(它实际上是游戏的保存文件)并用多个在线检查器检查它...这是XML文件:

<?xml version="1.0" encoding="utf-8"?>
<Save xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DumaLegend">
  <saveInfo>
    <energyPieces>0</energyPieces>
    <fullEnergyCells>4</fullEnergyCells>
    <fullHearts>4</fullHearts>
    <globalSwitches xmlns:d3p1="a">
      <d3p1:switchList xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
    </globalSwitches>
    <gold>0</gold>
    <hasBigFireball>false</hasBigFireball>
    <hasCombo>false</hasCombo>
    <hasCrossbow>false</hasCrossbow>
    <hasDash>false</hasDash>
    <hasDashUpgrade>false</hasDashUpgrade>
    <hasDoubleJump>false</hasDoubleJump>
    <hasFireball>false</hasFireball>
    <hasHookshot>false</hasHookshot>
    <hasInvisPot>false</hasInvisPot>
    <hasSecondCombo>false</hasSecondCombo>
    <hasShieldUpgrade>false</hasShieldUpgrade>
    <hasSmallFireball>false</hasSmallFireball>
    <heartPieces>0</heartPieces>
    <heroPosOnMap>0</heroPosOnMap>
    <heroTokens>0</heroTokens>
    <itemSlot1 xmlns:d3p1="http://schemas.datacontract.org/2004/07/DumaLegend.Objects.Consumables" i:nil="true" />
    <itemSlot2 xmlns:d3p1="http://schemas.datacontract.org/2004/07/DumaLegend.Objects.Consumables" i:nil="true" />
    <lives>3</lives>
    <worldsUnlocked>0</worldsUnlocked>
    <worldsUnlockedOnMap>0</worldsUnlockedOnMap>
  </saveInfo>
  <saveSlot>0</saveSlot>
</Save>

注意:很抱歉将其复制粘贴为html代码我实际上没有把它放在代码示例中!

编辑:预期输出:0

1 个答案:

答案 0 :(得分:1)

您需要一个完全限定的名称(即包括命名空间)。因此

XDocument xdoc = XDocument.Load(FileLoc);
MessageBox.Show(xdoc.Descendants(XName.Get("energyPieces", "http://schemas.datacontract.org/2004/07/DumaLegend")).First().Value);

或者,如果您愿意

XDocument xdoc = XDocument.Load(FileLoc);
MessageBox.Show(xdoc.Descendants("{http://schemas.datacontract.org/2004/07/DumaLegend}energyPieces").First().Value);