Search code examples
c#linq-to-xmlxmlreaderxelementsystem.xml

Read each node in IEnumerable<XElement> using XMlReader


I have IEnumerable<XElement> theTestCaseNodes which has the following kind of XElements

<testcase>
    <Main>  
       <test_step type ="action">
           <Name>Goto</Name>
           <description>xxxxxxxxx</description>    
       </test_step>  
       <test_step type ="check">
           <Name>Click</Name>
           <description>xxxxxxxxx</description>
       </test_step>  
    </Main>  
</testcase>
<testcase>
    <Main>  
       <test_step type ="action">
           <Name>Goto</Name>
           <description>xxxxxxxxx</description>    
       </test_step>  
       <test_step type ="check">
           <Name>Type</Name>
           <description>xxxxxxxxx</description>
       </test_step>  
    </Main>  
</testcase>

Basically this is my testcase and I want to execute them in an order. So, now I want to read each node in IEnumerable using XMLReader.

Please help how to proceed!!

I understood that i need to use "using" but not sure how to proceed.

public void ExecuteTestcase(IEnumerable<XElement> theTestCaseNodes)
{
    using (XmlReader aNodeReader = XmlReader.ReadSubtree()) {

    }
}

Solution

  • Use XElement.CreateReader for instantiating XmlReader for the element.

    public void ExecuteTestcase(IEnumerable<XElement> theTestCaseNodes)
    {
        foreach(var node in theTestCaseNodes)
        {
            using (var reader = node.CreateReader())
            {
                // use XmlReader for testing
            }
        }
    }
    

    XNode.CreateReader Method ()

    If main purpose of XmlReader is reading elements in correct order then looping through elements will execute them in same order they appear in xml

    foreach(var testStep in theTestCaseNodes.Elements("test_step"))
    {
        // execute step
    }
    

    If you don't want rely on order of your xml then you can access correct step by type attribute

    foreach(var testStep in theTestCaseNodes.Elements("Main"))
    {
        var action = testStep.Elements("test_step")
                             .First(step => step.Attribute("type") == "action");
        var check = testStep.Elements("test_step")
                            .First(step => step.Attribute("type") == "action");
    
        // execute action
        // execute check
    }