-1

I want to copy select parts of one file into another with C#

For example, suppose I have a file with following contents:

<div id="1"> contents of this div.. </div>
<div id="2"> contents of this div.. </div>
<div id="3"> contents of this div.. </div>

Now if I want to copy only the line <div id="2"> contents of this div.. </div> into a new file. Then how can i do this efficiently?

sehe
  • 374,641
  • 47
  • 450
  • 633
Gaurav
  • 8,367
  • 14
  • 55
  • 90
  • 1
    how do you identify which part of the content should be copied? (length,id,div,startswith...) – HW90 May 31 '12 at 08:42
  • 1
    @user1400722 Can you ask a question with relevant details? Show a sample source document. Is it XHTML? Also, using words helps (u/ur doesn't show appreciation others helping you). – sehe May 31 '12 at 08:46
  • The fact you are wanting to output [tag:asp] does not make this an asp question – thecoshman May 31 '12 at 08:46
  • @user1400722: We need to know how your program is to decide whether it needs to copy the first, the second or the third row. If you are not able to determine that or give a criteria for that, we can't help you. As HW90 asked: Which part of the file should be copied? – Thorsten Dittmar May 31 '12 at 08:46
  • I will identify it by id, like id="2", but i don`t to how to identify and how to find the end of block – Gaurav May 31 '12 at 08:50
  • @user1400722 Well, you just said "block" which is more information than you mention in the post. Just post a (stripped) sample input document. – sehe May 31 '12 at 09:25

3 Answers3

2

Select the content using XPath and then export to second file.

e.g.

XmlDocument document = new XmlDocument();
document.LoadXml(data);
XmlNode node = document.SelectSingleNode("//div[@id='2']");
SaveToFile(node.InnerText);

Read here for XPath example

Sandeep Singh Rawat
  • 1,637
  • 1
  • 14
  • 27
  • thanks @sandeep but if u can give ur answer with little example code then it will be more helpful for me – Gaurav May 31 '12 at 08:44
1

using a regex, for example, to extract what you want

<div id="2">(.*)</div>
Luis Filipe
  • 8,488
  • 7
  • 48
  • 76
1

There are different ways to solve this problem:

  1. you can use Regex to select the part that should be copied
  2. XPath also can be used to select the content
  3. If it is html you also can use the HTML Agility Pack

HTML Agility Example:

var doc = new HtmlWeb().Load(url);
var comments = doc.Descendants("div")
                  .Where(div => div.GetAttributeValue("class", "") == "comment");

Here you can find a overview of different methods to parse HTML-fields via C# (including examples)

HW90
  • 1,953
  • 2
  • 21
  • 45