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

时间:2017-12-20 10:25:26

标签: c# xml linq xmldocument

我的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变为null)。

我可以更改或使用什么不更改旧值,因为我希望稍后在代码中使用该值。请帮我。在此先感谢。

1 个答案:

答案 0 :(得分:1)

ToList()的查询上致电MovementVersionNew

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);

}