XPath如何在属性值为{x:Null}时返回空值

时间:2017-10-11 06:56:31

标签: c# xml xpath

xml显示Name的属性值为{x:Null}。我正在尝试使用XPath来恢复null而不是“{x:Null}”。 有没有办法使用命名空间?

我的单元测试:

  var xml = "<RootActivity xmlns=\"clr-namespace:InfoStore.Reports.Activities.ReportPack.CoreActivities;assembly=InfoStore.Reports.Activities\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:sap2010=\"http://schemas.microsoft.com/netfx/2010/xaml/activities/presentation\">" +
              "<Parent Depth=\"1\">" +
                "<Child Name=\"{x:Null}\" sap2010:WorkflowViewState.IdRef=\"ReportPackForEachItemActivity_2\" Id=\"10\" Group=\"A\">ChildValue #10</Child>" +
                "<Child Id=\"20\"  Group=\"B\">ChildValue #20</Child>" +
                "<Child Id=\"21\"  Group=\"A\">ChildValue #21</Child>" +
                "<Parent Depth=\"2\">" +
                  "<Child Id=\"11\">ChildValue #11</Child>" +
                  "<Child Id=\"12\">ChildValue #12</Child>" +
                "</Parent>" +
              "</Parent>" +
            "</RootActivity>";

  var xDoc = XDocument.Parse(xml);

  XNamespace rootNamespace = xDoc.Root.GetDefaultNamespace();
  var xmlnsNameSpace = rootNamespace.NamespaceName;

  var xNameSpace = "http://schemas.microsoft.com/winfx/2006/xaml";

  XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(new NameTable());
  nameSpaceManager.AddNamespace("xml_ns", xmlnsNameSpace);

  var firstChild = xDoc.XPathSelectElements("/xml_ns:RootActivity/xml_ns:Parent/xml_ns:Child[position()=1]", nameSpaceManager).FirstOrDefault();
  Assert.IsNotNull(firstChild, "Expected Child element");

  //TODO how to use this namespace to get null value
  XNamespace nsX = XNamespace.Get(xNameSpace);

  var nameAttribute = firstChild.Attribute("Name");
  Assert.IsNotNull(nameAttribute, "Expected attribute");

  //TODO - How to resolve value of {x:Null} to bring back Null.

  //Assert.IsNull(nameAttribute.Value, "Expeceted value for attribute");

0 个答案:

没有答案