1

I have HTML/CSS that I retrieve from a page. I want to get the value, debt, from the file.

The file is something like the following:

...

<tr>
<td width="10%"><input type="hidden" name="number" value="000115900">
  <input type="hidden" name="debt" value="2.282,00">
  <input type="hidden" name="id" value="01039">
  <input type="hidden" name="idbill" value="129">
...

I want the debt value, in this case: 2.282,00

I did:

int first = responseFromServer.IndexOf("<input type=\"hidden\" name=\"debt\" value=\"");
int last = responseFromServer.IndexOf("\">");
string str2 = responseFromServer.Substring(first + 1, last - first -1);

And it is not working. I get that the value must be non negative or non zero. Whats is wrong?

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120

3 Answers3

3

Your last assignment should begin its search from first:

int last = responseFromServer.IndexOf("\">", first); 

In your code sample, last is getting the index of the first "> in the string, so its value is smaller than first, and last - first - 1 is a negative number.

phoog
  • 42,068
  • 6
  • 79
  • 117
3

That's because last is probably matching the first /> in the string, not the first one after the <input you're looking for. You need to start searching after first (second param in IndexOf IIRC).

Have you tried using the Html Agility Pack for parsing HTML instead?

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
1

try

string partOne = "<input type=\"hidden\" name=\"debt\" value=\"";
string strX = responseFromServer.SubString ( responseFromServer.IndexOf(partOne) + partOne.Length);
string str2 = strX.SubString ( 0, strX.IndexOf("\">") ); // str2 now contains 2.282,00

IF you need to parse HTML a very useful (and free) library is http://htmlagilitypack.codeplex.com/

Yahia
  • 69,653
  • 9
  • 115
  • 144
  • I´m getting this in **str2**, `="http://mywebpage/info.php" method="POST`Which is part of the second line of the HTML page –  Nov 10 '11 at 21:27
  • @Kani then the result of `responseFromServer.IndexOf(partOne)` must be < 0 which in turn means that `partOne` is NOT present in `responseFromServer`... this can be for example if somewhere in the middle of the string some additional "white space" exists... thus you are much better off using the library (see the link in my answer). – Yahia Nov 10 '11 at 21:36
  • @ Yahia : well, I think is too much of a gun using it. Because I need the value once in all the program. Nevertheless, maybe is my unique option. I will read the docs to see how it works. –  Nov 10 '11 at 21:43