Reputation: 768
I have a set of files that have the structure of an XML file (parent-child nodes), but are not the conventional XML files. The structure looks like this:
<_ML_Message>
<TransactionId Value="0x02" />
<GroupNo Value = "2" />
<AbortOnError Value = "255" />
<MessageBody>
<GetProcParameterRequest>
<ServerId Value="0xFFFFFFFFFFFF" />
<ParameterTreePath Qty = "1" >
<_OctetString Value="0x0000800029FF" />
</ParameterTreePath>
</GetProcParameterRequest>
</MessageBody>
<CRC16 Value = "0" />
<EndOfMlMessage />
</_ML_Message>
<_ML_Message>
<TransactionId Value="0x03" />
<GroupNo Value = "3" />
<AbortOnError Value = "255" />
<MessageBody>
<CloseRequest>
</CloseRequest>
</MessageBody>
<CRC16 Value = "0" />
<EndOfMlMessage />
</_ML_Message>
Since I cannot use the standard C# XML libraries (for example, XMLDocument) on this file I am trying to parse it and use it like a normal text file,
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string xml = File.ReadAllText(baseDirectory + "MyXMLFile.xml");
if (xml.StartsWith("TransactionId"))
{
//Try to get the value
}
But parsing it this way is cumbersome at the moment, I was wonder if there are alternative ways to parse this kind of a file.
Upvotes: 2
Views: 189
Reputation: 104
You can try this but if you want to get all transactionIds you need to read all
string transactionId ;
string rootStart = "<doc>";
string rootEnd = "</doc>";
string xml = rootStart + File.ReadAllText("test.txt") + rootEnd;
XElement el = XElement.Parse(xml);
var isExist = el.Descendants("TransactionId").Any();
if (isExist)
{
transactionId = el.Descendants("TransactionId").FirstOrDefault().FirstAttribute.Value;
}
Upvotes: 1
Reputation: 46
If I understood you correctly posiible solution is to add fake root element and parse new document with XMLDocument.
<root>
<_ML_Message>
...
</_ML_Message>
<_ML_Message>
...
</_ML_Message>
</root>
Upvotes: 3
Reputation: 49321
If you have a file which contains a series of valid XML elements but no root element, wrap the file with a root element. You can then use the normal XML libraries to parse it.
Alternatively, break the stream up on the message boundaries which appear to be blank lines and parse each chunk. Either of these will be less work than trying to parse the elements yourself.
Upvotes: 2