Reputation: 690
I need to get user id corresponding terminal id. any help. But it's giving error:
The ReadElementContentAsString method is not supported on node type None. Line 1, position 668.
string strTerminalId = "E";
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(STRING); //
string strxml = xdoc.OuterXml;
string strUserName = "";
bool Flag = false;
using (XmlReader reader = XmlReader.Create(new StringReader(strxml)))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Row":
reader.Read();
if (Flag == false)
{
reader.ReadToFollowing("TERM-ID");
reader.Read();
string strTERMID = reader.ReadElementContentAsString().ToString();
if (strTERMID == strTerminalId)
{
while (reader.ReadToFollowing("NA") && (Flag == false))
{
reader.Read();
string strUser = reader.ReadContentAsString();
if (strUser == "NA")
{
reader.ReadToFollowing("c:value");
reader.Read();
strUserName = reader.ReadContentAsString();
Flag = true;
}
}
}
}
break;
}
}
}
The content of the XML document is
<GetReferenceTableResponse xmlns='http://tempuri.org/'>
<GetReferenceTableResult>
<Table Name='C' ID='46899' xmlns=''>
<Columns>
<Col ID='7442' Name='TD' Datatype='T' Length='8' AttributeDescription='Terminal ID' IsKey='Y'/>
<Col ID='7443' Name='D' Datatype='T' Length='50' AttributeDescription='Description' IsKey=' '/>
<Col ID='7444' Name='U' Datatype='T' Length='8' AttributeDescription='USER-ID' IsKey='' />
</Columns>
<Rows>
<Row RowsetID=\"1\">
<TERM-ID ID='279598'>A</TERM-ID>
<DESC-TXT ID='279622'>ASC</DESC-TXT>
<USER-ID ID='279646'>A</USER-ID>
</Row>
</Rows>
</Table>
</GetReferenceTableResult>
</GetReferenceTableResponse>
Upvotes: 1
Views: 1465
Reputation: 10376
ReadToFollowing
navigates to the nearest element with a given name and the next Read
will go inside that element - straight to the Text. So you would need ReadContentAsString
in both cases.
In your case that would work:
using (XmlReader reader = XmlReader.Create(new StringReader(strxml)))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Row":
if (!Flag)
{
reader.ReadToFollowing("TERM-ID");
reader.Read();
string strTERMID = reader.ReadContentAsString();
if (strTERMID == strTerminalId && reader.ReadToNextSibling("USER-ID"))
{
reader.Read();
strUserName = reader.ReadContentAsString();
Flag = true;
}
}
break;
}
}
}
}
I have removed the first Read
just after case "Row":
- otherwise you would miss the proper element and as well removed ReadToFollowing("USER-ID")
from the while loop - it is okey to go into the element only once.
But as @kennyzx said - it is much simpler to parse the xml using XDoccument.
UPDATE
I am not sure about your schema but if it is possible for a Row element to not have User-Id, then with ReadToFollowing
it is possible to skip to the next available 'User-ID' element, even if it is not in the same 'Row' element. So it is better to use ReadToNextSibling
in the second case.
Upvotes: 1