0

I am new to regular expression and want to create two regexes for my .net application.

I have an input variable which stores an xml. Below is the xml

<Row>
......
</Row>
<Row {optional}>
.... 
</Row>
<Row {optional} header="true" {optional}>
</Row>

I want 2 regexes: 1. Regex which selects Rows with header="true" 2. Regex which selects Rows which do not have header="true"

Regex only have to consider opening tag. eg:

Mike143
  • 163
  • 3
  • 14

1 Answers1

0

Regex is not the best option for processing xml in .NET If your're using .NET 3.5 or higher, check out LINQ to xml For an older version of the runtime see XmlDocument and XPath

Using LINQ your code would be something like this:

    var document = XDocument.Load("path to your file"); // or XDocument.Parse if you have content in a string
    var elementsWithHeaders = document.Descendants("Row").Where(x => 
         x.Attribute("header")!=null && x.Attribute("header").Value == "true");

This code is not optimal, however to make it more efficient I would need to know more assumptions about the structure of your xml

If you are using C#6 you could also use null-conditional operator to simplify the predicate above

    var elementsWithHeaders = document.Descendants("Row").Where(x => 
         x.Attribute("header")?.Value == "true");
ironstone13
  • 3,325
  • 18
  • 24