简体   繁体   中英

get node from xml in c#

I have an xml file like:

<?xml version="1.0" encoding="utf-8"?>
<Config>   
   <MetadataFormConfig FieldInternalName="Test">
      <Tabs>
         <Tab Title="A to C" Order="1">
            <ShowParentTerm>A</ShowParentTerm>
            <ShowParentTerm>B</ShowParentTerm>
            <ShowParentTerm>C</ShowParentTerm>
         </Tab>
         <Tab Title="D to E" Order="2">
            <ShowParentTerm>D</ShowParentTerm>
            <ShowParentTerm>E</ShowParentTerm>
         </Tab>
      </Tabs>   
   </MetadataFormConfig>  
</Config>

I want to get all the nodes by FieldInternalName.

Can please give a way how I can do this?

You can use SelectNodes("/Config/MetadataFormConfig[@FieldInternalName='Test']")

Check the details on SelectNodes

Linq version for getting all the nodes by FieldInternalName.

 // Loading from a file, you can also load from a stream
        XDocument loaded = XDocument.Load(@"d:\test.xml");
        // Query the data 
        var query = from c in loaded.Descendants("MetadataFormConfig")
                where (string)c.Attribute("FieldInternalName") == "Test"
                select c;

you can test your own xpath expression and refine it until you get your desired result, there are plenty of XPATH testers online, for example here is one: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

just go there, paste your xml fragment from above and work with XPATH untill you get what you need.

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