I have an Xml document which contain some records like this :
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Koneksi>
<TipeKoneksi>Prepaid Connection</TipeKoneksi>
<Datasource>xe</Datasource>
<DBUser>a#</DBUser>
<DBPassword>12345678</DBPassword>
<Namakoneksi>localhost</Namakoneksi>
<Host>127.0.0.1</Host>
<Username>admin</Username>
<Password>sa</Password>
</Koneksi>
<Koneksi>
<TipeKoneksi>Standalone Connection</TipeKoneksi>
<Datasource>none</Datasource>
<DBUser>none</DBUser>
<DBPassword>none</DBPassword>
<Namakoneksi>langsung</Namakoneksi>
<Host>127.0.0.1</Host>
<Username>admin2</Username>
<Password>sa</Password>
</Koneksi>
</Root>
And the problem is How to get the element value of DBUser, Datasource, DBPassword only if i make the condition statement is if
- Host
- Username
I've made the code something like this :
public bool OpenConnection()
{
string datasource = "";
string dbusername = "";
string dbpassword = "";
try
{
if(needdb==true){
reader = XmlReader.Create("connection.xml");
}
reader.MoveToContent();
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element) {
if((reader.Name=="Host") && (reader.ReadElementString()==this.txtFTPAddress.Text)){
if((reader.Name=="Username") && (reader.ReadElementString()==this.txtUsername.Text)){
if (reader.Name == "Datasource") {
datasource=reader.ReadElementString();
}
if (reader.Name == "DBUser") {
dbusername=reader.ReadElementString();
}
if (reader.Name == "DBPassword") {
dbpassword=reader.ReadElementString();
}
}
}
}
}
conn = new OracleConnection("Data Source="+datasource+"; User Id="+dbusername+"; Password="+dbpassword+";");
conn.Open();
return true;
}
catch (Exception)
{
return false;
}
}
and get nothing as the result, Please help me.

1 answers
The problem there is that each iteration of the while loop reads the same element and not the child nodes within the same parent node. Worse still, XmlReader can only read in a forwards direction whereas you only want to use the Datasource, DBUser and DBPassword nodes if the Host and Username nodes (which always follow them in the file) have certain values.
However, it's possible to overcome these difficulties by using a switch statement and a couple of bool variables:
answered 6 months ago by:
12813
0
Again and again...thanks a lot Mr. Vulpes it works.