Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've a string say "<Node a="<b>">". I need to escape only the data and parse this string as a node in XMLWriter. Hence how to escape only the attribute value "<" and note the XML structure's "<".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
258 views
Welcome To Ask or Share your Answers For Others

1 Answer

using (var writer = XmlWriter.Create(Console.Out))
{
    writer.WriteStartElement("Node");
    writer.WriteAttributeString("a", "<b>");
}

Output <Node a="&lt;b&gt;" />


Firstly you should parse the string. Since this is not valid xml, you can't use an xml parser. You can try HtmlAgilityPack. Then you can write the values with xml writer.

string s = "<Node a="<b>">";

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(s);

var node = doc.DocumentNode.FirstChild;
var attr = node.Attributes[0];

using (var writer = XmlWriter.Create(Console.Out))
{
    writer.WriteStartElement(node.Name);
    writer.WriteAttributeString(attr.Name, attr.Value);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...