问题
I am working on project using asp.net mvc3 C# . I want to change some html element
attributes by c# like width , height etc. I have a simple (_Layout.cshtml) file
<html> <head>
<link href="@Url.Content("file.css")" rel="stylesheet" type="text/css" />
<body>
<a href="#" id="link1" title="@Function.ConfigElement("FacebookLink")" ></a>
</body>
</head> </html>
So i am using html agility pack to load and save this file
HtmlDocument doc= new HtmlDocument();
doc.load("_Layout.cshtml");
doc.GetElementbyId("link1").Attributes.Add("title", "@Function.ConfigElement("NewLink")");
doc.save("_Layout.cshtml");
After saving file output is like this
<html> <head>
<link href="@Url.Content("file.css")"="" rel="stylesheet" type="text/css" />
<body>
<a href="#" id="link1" title="@Function.ConfigElement("NewLink")"="" ></a>
</body>
</head> </html>
in (link href)
and (anchor title)
saving some extra characters
How can i avoid this problem .. Is there any other solution for parse html in c# for asp.net mvc.
Actually I want to add some server side function in these html element attributes
回答1:
As StackOverflow's syntax highlight subtly hints, your HTML is extremely invalid.
href="@Url.Content("file.css")"
This is actually two attributes: href="@Url.Content("
and file.css")"
. (which has no value)
You can't use an HTML parser to parse Razor markup.
Instead, you should use the actual Razor parser.
回答2:
CSCHTML is not HTML. It is mix of CS, special scripts and optionally HTML - so HtmlAgilityPack is not a good tool to read/manipulate it.
Why it happens in particular:
<link href="@Url.Content("file.css")"
Form HTML point of view there are 2 attributes and (href and file.css) plus strange ")" unexpected text. Somehow AgilityPack tries to make sense of it and outputs whatever you got.
来源:https://stackoverflow.com/questions/13750804/html-agility-pack-creating-irrelevant-characters-on-save-html-file-in-c-sharp