user1526912
user1526912

Reputation: 17280

how to replace string pattern in c#

My c# program retrieves an xml data column from my db containing a path to a text file as follwows

<path>
  <path name="myfile" url="/test/dir/YUUHGGGVFY/grgrggr.text" />
</path>

So the above is stored in a string variable name = pathstring

How can I format the above string to only extract the "/test/dir/YUUHGGGVFY/grgrggr.text" portion ?

The other sections of the string will always be the same:

so pathstring = "/test/dir/YUUHGGGVFY/grgrggr.text" portion ?

Upvotes: 1

Views: 140

Answers (2)

Claudio Bernasconi
Claudio Bernasconi

Reputation: 157

Take a look at LINQ2XML. I'll just provide you with a working solution for that particular use case:

string path = 
  @"<path>
      <path name=""myfile"" url=""/test/dir/YUUHGGGVFY/grgrggr.text"" />
    </path>";
XDocument xdoc = XDocument.Parse(path);
var pathString = (string)xdoc.Element("path").Element("path").Attribute("url");

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236278

You can use Linq to Xml to parse your string and get url attribute from path

string xml = 
  @"<path>
       <path name=""myfile"" url=""/test/dir/YUUHGGGVFY/grgrggr.text"" />
    </path>";
XElement pathElement = XElement.Parse(xml);
var pathString = (string)pathElement.Element("path").Attribute("url");

Upvotes: 3

Related Questions