2

I am trying to develop a project in which i am performing a sequence of processes. I want to load all the files of particular type (*.xhtml) from a directory . The files should open in tabs. I want to search for a particular tag and replace with another tag in all the files that is find and replace functionality. How to accommodate this.

Oybek
  • 7,016
  • 5
  • 29
  • 49
Manoj Nayak
  • 2,449
  • 9
  • 31
  • 53

2 Answers2

2

So what's the problem?

  1. Search files:

    var files = DirectoryInfo.GetFiles("*.xhtml", SearchOption.AllDirectories)

  2. Load in tabs. Not a big pro in windows forms but I think it's something like add new tab control to some tabs container per each found file.

  3. See Oybek's answer regarding last point!

Hope it helped.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Andrey Selitsky
  • 2,584
  • 3
  • 28
  • 42
  • This is a really good answer except the point 3. [Never ever never ever never ever use RegEx for XML/HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – Oybek Feb 07 '12 at 11:10
1

Well as far as the IO is concerned it is pretty straightforward, read directory, iterate over files and read content.

The following code snippet replaces the node of the xml.

var data = @"<foo>
    <items>
        <itemToReplace>
            <itemContent />
        </itemToReplace>
    </items>
</foo>";
        // Load your document
        var doc = XDocument.Parse(data);
        // Get the root
        var root = doc.Element("items");
        // Get all tags that you want to replace
        var repls = doc.Descendants("itemToReplace").ToList();
        // Iterate over
        foreach (var item in repls) {
            // prepare a new element as a replacement for your target.
            // Content will be the same as the content of the element being replaced.
            var newElement = new XElement("newElement", item.DescendantNodes());
            // add the element right after the tag to be replaced
            item.AddAfterSelf(newElement);
            // finally remove the tag.
            item.Remove();
        }
        MessageBox.Show(doc.ToString());

itemToReplace is replaced by newElement. As you say XHTML I suppose that there is a some sort of well formed XML/HTML that can be parsed via linq2xml. Cheers.

Oybek
  • 7,016
  • 5
  • 29
  • 49