1

My C# code is below.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="ICTRExchange.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <userSettings>
    <ICTRExchange.Properties.Settings>
      <setting name="ServerIP" serializeAs="String">
        <value />
      </setting>
      <setting name="ServerPort" serializeAs="String">
        <value>0</value>
      </setting>

How to match using regular expression in C#. I try regular expression in below. but It is not proper operation.

example

My target node is "ServerPort"

var regex = new Regex("<setting name=\"ServerPort\"(.*?)</setting>");
regex.match(xmlstring)
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
taehyung
  • 135
  • 1
  • 1
  • 10

2 Answers2

2

Parsing mark up alnguage with regex is very bad idea (see: Using regular expressions to parse HTML: why not? - it's aboout HTML, but also applies to XML).

Instead, you could use XML library provided in .NET, like System.Xml.

Here's code snippet you could build your application on (I stored your XML in testxml.xml file):

static void Main(string[] args)
{
  XmlDocument xml = new XmlDocument();
  xml.Load(@"C:/users/MyUser/desktop/testxml.xml");
  var settings = xml.SelectNodes("configuration/userSettings/ICTRExchange.Properties.Settings")[0].ChildNodes;
  XmlNode settingsWithServerPort = null;
  foreach (XmlNode node in settings)
    if (node.Attributes["name"].Value == "ServerPort")
      settingsWithServerPort = node;
}
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

You can try this

<setting.*?>[\w\W]+?<\/setting>

Explanation

  • <setting.*?> - Matches <setting followed by anything except new line followed by >.
  • [\w\W]+? - Matches anything one or more time. (lazy mode).
  • <\/setting> - Matches </setting>

Demo

Code Maniac
  • 37,143
  • 5
  • 39
  • 60