2

I have a string, which could look like this:

"Sandra <as type="1">walked</as> in the park, and met a <as type="3">random</a> stranger".

Based on these xml tags, I would like to replace the tag with something else (a list of controls).

For instance, when I see <as type="1">walked</as> , I want to return a literal and a textbox to be replaced in that sentense.

I guess the simplest way would be to add the whole thing in a placeholder, but I've no idea how to do the replacement part.

6
  • what are you going to do with changed xml? are you going to show those control on aspx page? Commented May 2, 2012 at 6:40
  • If you want them to be ASP.NET controls, you should just parse the whole string and add the controls dynamically. If you want to use javascript to operate on the controls and don't need them serverside, you can try to use a one Literal control with a html to be displayed. Either way I suppose you should parse the string manually. Commented May 2, 2012 at 6:42
  • Yes, and then later react on the input the user gives in those controls Commented May 2, 2012 at 6:42
  • Do you want to insert different type of controls for different type attributes? Commented May 2, 2012 at 6:46
  • 1
    also the string you have provided is not a valid xml rather a string having predefined tags. Commented May 2, 2012 at 6:46

1 Answer 1

1

You currently don't have valid XML, so as a first step I recommend you surround it with some basic tags, for example:

var start = "Sandra <as type=\"1\">walked</as> in the park, and met a <as type=\"3\">random</as> stranger";
var startAsXml = "<root>" + start + "</root>";

Now we can parse it:

var doc = XElement.Parse(startAsXml);

Now we have two types of nodes in this XML - Text and Elements. You can easily loop through any number of ways and extract them, change them, do what you like. Here's an example:

foreach (var node in doc.Nodes()) 
{
    if (node.NodeType == XmlNodeType.Text) Console.WriteLine("Text: {0}", node.ToString().Trim());
    else if (node.NodeType == XmlNodeType.Element) 
    {
        var element = (XElement)node;
        Console.WriteLine("Element: Name={0} Type={1} Value={2}",
                          element.Name, element.Attribute("type").Value, element.Value);
    }
}

This will print:

Text: Sandra 
Element: Name=as Type=1 Value=walked
Text:  in the park, and met a 
Element: Name=as Type=3 Value=random
Text:  stranger
Sign up to request clarification or add additional context in comments.

Comments

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.