I'm working with c# .Net
I have a question,
I'm loading Xml file with XDocument.xDoc.Load(file)
, but it fails because in my content I also have xml tags:
Example: <root><abc><deg></abc></root>
My problem is that the Load
function treats the <deg>
as an Xml tag without a matching "</deg>
"...
My question is, how can i replace the "<" and ">" of the "deg" with the matching "<
" ">
" in the easiest way?
N.B. my file is very big and I have a lot of tags开发者_运维知识库...
Thanks!
What you're trying to do is difficult to do with the standard .NET libraries, unless you want to do a lot of difficult parsing. If there is any rhyme or reason to your non-ended tags, it would help a lot. For example, is there a known list of tags that are not closed? If so, the searching and replacing would not be bad.
But, if it is truly open-ended, if any tag could be unclosed, then you'll need to use something like HTML Tidy. The .Net wrapper of this is can be found here. With this,solution, the <deg>
tag would be converted to <deg/>
. HTML Tidy wrapper can also fix a few other problems that cause xml to be mal-formed.
Once your file contains well-formed xml, then you can load it into xml objects easily. Then if you have other work to do on the document, you'll at least be able to see it as xml.
Standard regex disclaimer goes here... - sometimes they can come in handy for HTML cleanup scenarios.
Give this approach a try:
string input = "<root><abc><deg><foo></abc><bar></root>";
string pattern = @"(<(?<tag>\w+)>)(?!.*?</\k<tag>>)";
string result = Regex.Replace(input, pattern,
match => HttpUtility.HtmlEncode(match.Value));
XDocument document = XDocument.Parse(result);
Console.WriteLine(document.ToString());
Of course be mindful of the file size and that other suggestions maybe more suitable if performance is important for the overall process.
EDIT: the Html Agility Pack is an alternate option for sanitizing any malformed content. If you know the content you could go in there and replace them with valid closing tags.
If you can get at that section before you load it into the XmlDocument
then you could use the HttpUtility.HtmlEncode
method to entity-escape the content for you.
The other thing you might want to consider is wrapping your XML-looking content as CDATA
, which will effectively hide this content from the parser.
If this file is really big then you should use XmlReader instead of XmlDocument and there is no "not closed tags" issue.
http://msdn.microsoft.com/en-us/library/system.xml.xmlreader%28VS.80%29.aspx
Example: How to do streaming read of a large XML file in C# 3.5
精彩评论