通过排除XML中存在的与名称空间相关的属性来读取XML元素值

时间:2018-08-31 10:01:06

标签: c# xml

我正在尝试读取XML中存在的元素的值。如果输入在XML中不包含任何与名称空间相关的属性,则它可以正常工作,如下所示-

string testInputXML = @"
    <FIXML>
        <Header>
        <RequestHeader>
          <MessageKey>
            <RequestUUID>Req_1499940064961</RequestUUID>
            <ServiceRequestId>getLastNTransactionsWithPagination</ServiceRequestId>
            <ServiceRequestVersion>10.2</ServiceRequestVersion>
            <ChannelId>COR</ChannelId>
            <LanguageId></LanguageId>
          </MessageKey>
        </RequestHeader>
      </Header>
     <isLogging>true</isLogging>
    </FIXML>
    ";
                XElement myElement = XElement.Parse(testInputXML);
                Console.WriteLine(myElement.Element("isLogging").Value);

如果输入XML包含任何与名称空间相关的属性,则抛出异常。

  

对象引用未设置为对象的实例。

string testInputXML = @"
<FIXML xsi:schemaLocation=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://www.w3.org/fixml"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
    <Header>
    <RequestHeader>
      <MessageKey>
        <RequestUUID>Req_1499940064961</RequestUUID>
        <ServiceRequestId>getLastNTransactionsWithPagination</ServiceRequestId>
        <ServiceRequestVersion>10.2</ServiceRequestVersion>
        <ChannelId>COR</ChannelId>
        <LanguageId></LanguageId>
      </MessageKey>
    </RequestHeader>
  </Header>
 <isLogging>true</isLogging>
</FIXML>
";
            XElement myElement = XElement.Parse(testInputXML);
            Console.WriteLine(myElement.Element("isLogging").Value);

在获取元素值时是否有任何方法可以排除XML中存在的命名空间?

2 个答案:

答案 0 :(得分:0)

尝试一下:

Console.WriteLine(myElement.DescendantsAndSelf().Elements().FirstOrDefault(d => d.Name.LocalName == "isLogging")?.Value);

答案 1 :(得分:0)

尝试像这样使用XPath:

XDocument xmlDoc = XDocument.Parse(xml);
XElement element = xmlDoc.XPathSelectElement("/*[name()='FIXML']/*[name()='isLogging']");