0

How to write an xpath expression for :

 <script src="../../Scripts/ex.js"></script>

which will match the src value (../../Scripts/ex.js). Because i want to relace ../../Scripts with some other string.

2
  • Do you want to add "version" of js file? Commented Aug 29, 2012 at 8:06
  • i just want to select all script tags and replace there src values Commented Aug 29, 2012 at 8:08

4 Answers 4

2

you can go with the following code.

 TextReader tr = new StringReader(response);
    XElement xelement = XElement.Load(tr);
    var Script = xelement.Descendants("script").ToList();
    if (Script.Count() > 0)
    {
     Script.First().Attribute("src").Value = "../../Scripts/NewEXWithReplace.js";

    }
Sign up to request clarification or add additional context in comments.

3 Comments

You replace one string with another, not the src of script
this way will not replace src in source document, result will be only new string instance, I assume that OP wants to replace this src in actual document not to obtain modified string.
Now you replace only the first script but I think that you should chage only scripts that has ../../Scripts/ex.js in the src attribute also I think it should be done for all occurrences...
1

LINQ to XML

var xdocument = XDocument.Load("XMLFile1.xml"); // you can use Parse or whatever
var elements = xdocument.XPathSelectElements("//script[@src='../../Scripts/ex.js']");
foreach (var element in elements)
{
  element.Attribute("src").SetValue("foo");
}

Comments

1

You can also use HtmlAgilityPack which allows you to access attributes usefully codeplex tool.

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(@"<script src="../../Scripts/ex.js"></script>" />");

foreach (var script in doc.DocumentNode.Descendants("script"))
{

    script.Attributes["src"].Value = "loading.gif";
}

Another way is to use linq to xml

Comments

0

I know you said you wanted an XPath expression, but what about a simple string replace?

e.g.

string s = "<script src=\"../../Scripts/ex.js\"></script>";
string newS = s.Replace("../../Scripts", "../../Scripts2"); // Or whatever you want to replace it with

2 Comments

OP wants to replace xxxxx string from the XML document.
Yes I understand that, but the XML document in question looks like an ASP.NET (or Razor) page. I'm just presenting a different way of solving the problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.