在C#中修改xml文件中的值时出现System.InvalidOperationException

时间:2017-07-05 15:17:37

标签: c# 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>

好吧?好!但为什么它会发出错误,这意味着它找不到东西呢?这是一件非常有效的事情......

这是xml文件:

public class Team{
...

(relationship with Player has been hidden)
...

@Column(name = "AMOUNT_PLAYERS")
private Short amountPlayers;

@Column(name = "AMOUNT_FIRSTSTRING_PLAYERS")
private Short amountFirstStringPlayers;

@Column(name = "AMOUNT_SECONDSTRING_PLAYERS")
private Short amountSecondStringPlayers;

...

}

2 个答案:

答案 0 :(得分:1)

使用xdoc.Descendants(XName.Get("gold", "http://schemas.datacontract.org/2004/07/DumaLegend"))

答案 1 :(得分:0)

来自the docs for Elements

  

按文档顺序返回此元素或文档的子元素的过滤集合。只有具有匹配XName的元素才会包含在集合中。

文档中只有一个子元素,即Save元素。

您正在寻找的是路径Save/saveInfo/gold。所以你可以像这样使用Elements

XNamespace ns = "http://schemas.datacontract.org/2004/07/DumaLegend";
var gold = doc.Elements(ns + "Save")
    .Elements(ns + "saveInfo")
    .Elements(ns + "gold")
    .Single();

或者您可以使用Descendants,它将递归搜索所有子元素。

XNamespace ns = "http://schemas.datacontract.org/2004/07/DumaLegend";
var gold = doc.Descendants(ns + "gold").Single();
相关问题