简体   繁体   中英

Read XML element value by excluding namespace related attributes present in the XML

I am trying to read the values of the elements present in XML. It is working properly if input doesn't contains any namespaces related attributes in that XML as below -

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

If input XML contains any namespaces related attributes then it is throwing exception.

Object reference not set to an instance of an object.

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

Is there any way to exclude the namespaces present in the XML while fetching element values?

尝试这个:

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

Try using XPath like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM