当我将 XML 值设置为 null 时,变量值为 null

Variable value is null when I set XML value to null

我的XML

<example>
      <ReferenceNumber xmlns="http://www.example.com/schemas/core/movement">
        <Mnemonic>LHH1</Mnemonic>
        <MovementProjectNumber>4743</MovementProjectNumber>
        <MovementVersion>5</MovementVersion>
      </ReferenceNumber>
</example>

// 获取机芯版本值(5).

XDocument NewXML = XDocument.Parse(model.ReturnXML); // model.ReturnXML has XML as shown in above XML.
XNamespace ns = "http://www.example.com/schemas/core/movement";

var MovementVersionNew = from MovVer in NewXML.Root.Element(ns + "ReferenceNumber").Elements(ns + "MovementVersion")
                             select MovVer.Value.ToList().FirstOrDefault().ToString(); 

//获取XML节点部分以更新MovementVersion元素的值。

var MovementVersionRef = (from MovVer in NewXML.Root.Elements(ns + "ReferenceNumber")
                                               select MovVer).ToList();

// 将 MovementVersion 值设置为 null。

foreach (XElement element in MovementVersionRef.Descendants())
{
    if (!element.HasElements)
    {
        if (element.Name.ToString().Contains("MovementVersion"))
        {
            element.SetValue("");
        }
    }    
}    

上面的代码会将 MovementVersion 值设置为 null(在 NewXML 中)这是正确的,但同时它也改变了 MovementVersionNew 变量的值(我不希望这个从 5 更改为空)。

我可以更改或使用什么来不更改我的旧值,因为我希望稍后在代码中使用该值。请帮我。提前致谢。

MovementVersionNew 的查询中调用 ToList()

static void Main(string[] args)
{
    var xmlstr = 
        @"<example>
            <ReferenceNumber xmlns='http://www.example.com/schemas/core/movement'>
            <Mnemonic>LHH1</Mnemonic>
            <MovementProjectNumber>4743</MovementProjectNumber>
            <MovementVersion>5</MovementVersion>
            </ReferenceNumber>
         </example>";

    XNamespace ns = "http://www.example.com/schemas/core/movement";
    var xml = XDocument.Parse(xmlstr);    

    var MovementVersionNew = (from MovVer in xml.Root.Element(ns + "ReferenceNumber").Elements(ns + "MovementVersion")
                                select MovVer.Value.ToList().FirstOrDefault().ToString()).ToList();

    var MovementVersionRef = (from MovVer in xml.Root.Elements(ns + "ReferenceNumber")
                                select MovVer).ToList();

    foreach (XElement element in MovementVersionRef.Descendants())
    {
        if (!element.HasElements)
        {
            if (element.Name.ToString().Contains("MovementVersion"))
            {
                element.Value = String.Empty;
            }
        }
    }

    MovementVersionNew.ForEach(Console.WriteLine); //Prints "5"
    MovementVersionRef.ForEach(Console.WriteLine);

}