How can i read attribute value of a xml.
I have this below xml and i am working with windows forms vb.net
I tried something like this below but does not work. I want to read connection string value
Dim xe As XElement = XElement.Load("..\\..\\KMMiddleTier.xml")
Dim name = From nm In xe.Elements("ConnectionKey") Where nm.Element("ConnectionKey").Attribute("Key") = "DB_DEV" Select nm.Element("ConnectionKey").Attribute("ConnectionString").Value.FirstOrDefault()
Dim xmlDoc as XMLDocument
Dim xmlNodeList As XmlNodeList = xmlDoc.SelectNodes("/KMMiddleTierSecurity/ConnectionKeys/ConnectionKey")
Dim strConnectionKey As String = xmlNodeList.Item(0).Attributes("ConnectionString").Value''''
This might help.
Related
I have a file like this <ufile.io/g8dy86x0>
I'd like remove signature.
I try this code but doesn't work
Dim doc As XmlDocument = New XmlDocument
doc.Load(_filename)
Dim rnode As XmlNode = doc.SelectSingleNode("Signature")
doc.OwnerDocument.DocumentElement.RemoveChild(rnode)
What should i try ?
I thought this would be an easy task but I seem to have gotten lost in a rabbit hole.
I am trying to convert a class to XML and then a byte array in order to send it as the content of a HTTPWebRequest for a WCF Restful webservice. My code will return the class as XML in the Byte Array but the format is incorrect. The XML looks like this:
<?xml version="1.0" encoding="utf-8"?><Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><FirstName>Richard</FirstName><LastName>Cranium</LastName></Person>
I was attempting to use the OmitXmlDeclaration method thinking this would eliminate the extra declarations but it does not work with the xmltextwriter object and when I use the xmlwriterobject I can't determine how convert the outcome to a Byte array.
Here is my code:
Private Shared Function GenerateXMLPersonAsByte(strFirstName As String, strLastName As String) As Byte()
' This should serialize this to a byte array
Dim p As New Person()
p.FirstName = strFirstName
p.LastName = strLastName
' Want to use this with the xmlTextWriter but it does not support the property it is to be used with the XMLWriter instead
'Dim settings As XmlWriterSettings = New XmlWriterSettings()
'settings.OmitXmlDeclaration = True
'settings.ConformanceLevel = ConformanceLevel.Fragment
'settings.CloseOutput = False
' Create the XmlWriter object and write some content.
Dim mStream As New MemoryStream()
Dim ser As New XmlSerializer(GetType(Person))
Dim xmlTW As New XmlTextWriter(mStream, Encoding.UTF8)
ser.Serialize(xmlTW, p)
mStream = DirectCast(xmlTW.BaseStream, MemoryStream)
mStream.Close()
Return mStream.ToArray()
End Function
What must I do in order to get the XML with the correct opening tag?
or
How do I get the output from the XmlTextWriter object to a byte array?
I can't answer the whole question, but convert to string first
Dim myXmlString As String
Dim myStringWriter As New StringWriter()
Dim myXmlTextWriter As XmlTextWriter = New XmlTextWriter(myStringWriter)
'Write XML, and then flush the writer...
myXmlTextWriter.Flush()
'Return text from string writer...
myXmlString = myStringWriter.ToString()
'Close the Objects...
myStringWriter.Close()
myXmlTextWriter.Close()
then convert to byte using (sorry, C#, but you get the .NET call)
byte[] data = ASCIIEncoding.UTF8.GetBytes(myXmlString);
I am trying to do some XSLT transformation, to convert an XML to XML, using the following lines of code. When i try to create an XMLDocument object from the transformed XML i am getting an error
Data at the root level is invalid. Line 1, position 1.
Dim outputXML As New XmlDocument
Dim stream As New MemoryStream
Dim writer As XmlTextWriter = New XmlTextWriter(stream, System.Text.UnicodeEncoding.UTF8)
Dim navigator As XPathNavigator = illustratePlusXML.CreateNavigator()
Dim transormer As XslCompiledTransform = New XslCompiledTransform()
transormer.Load(ConfigurationManager.AppSettings("XSLT_File_Path"))
transormer.Transform(navigator, Nothing, writer)
Dim output As String = System.Text.UnicodeEncoding.UTF8.GetString(stream.ToArray())
outputXML.LoadXml(output)
Return outputXML
I could find a special character(square box), i persume this is causing the error. attached snapshot of the output xml. Can somebody please suggest ?
If you want to populate an XmlDocument as the result of an XSLT transformation then simply do
Dim resultDoc As New XmlDocument()
Using xw As XmlWriter = resultDoc.CreateNavigator().AppendChild()
Dim navigator As XPathNavigator = illustratePlusXML.CreateNavigator()
Dim transormer As XslCompiledTransform = New XslCompiledTransform()
transormer.Load(ConfigurationManager.AppSettings("XSLT_File_Path"))
transormer.Transform(navigator, Nothing, xw)
xw.Close()
End Using
There is no need to use a MemoryStream. If you really think you need to use a MemoryStream then make sure you reset its Position to 0 before calling the Load method.
This is a sample code in vb.net in which i retrieve the details of elements without attributes.
For Each standardItemInfoNode In ItemInfoNodes
baseDataNodes = ItemInfoNodes.ChildNodes
bFirstInRow = True
For Each baseDataNode As XmlNode In baseDataNodes
If (bFirstInRow) Then
bFirstInRow = False
Else
Response.Write("<br>")
End If
Response.Write(baseDataNode.Name & ": " & baseDataNode.InnerText)
Next
Next
How can i retrieve the details of the xml like having node with attributes and its child also having attributes. I need to retrieve all the attributes of node and its child node which are present in the middle of other xml tags.
I'm not sure exactly what you're asking, and I can't give you a specific example without knowing the format of the XML you are trying to process, but I think what you are looking for is the Attributes property of the XmlNode objects. Each XmlNode has an Attributes property that allows you to access all the attributes for that node. Here's the MSDN page that explains it (and provides a simple example):
http://msdn.microsoft.com/en-us/library/7f285y48.aspx
EDIT:
Using the example XML you posted in the comment, you could read the all the values and attributes like this:
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml("<EventTracker><StandardItem><Header1>Header1 Text</Header1> <Header2>Header2 Text</Header2></StandardItem><Item> <Events> <EventSub EventId='73' EventName='Orchestra' Description='0'> <Person PersonId='189323156' PersonName='Chandra' Address='Arunachal'/><Person PersonId='189323172' PersonName='Sekhar' Address='Himachal'/></EventSub> </Events> </Item> </EventTracker>")
Dim header1 As String = doc.SelectSingleNode("EventTracker/StandardItem/Header1").InnerText
Dim header2 As String = doc.SelectSingleNode("EventTracker/StandardItem/Header2").InnerText
For Each eventSubNode As XmlNode In doc.SelectNodes("EventTracker/Item/Events/EventSub")
Dim eventId As String = eventSubNode.Attributes("EventId").InnerText
Dim eventName As String = eventSubNode.Attributes("EventName").InnerText
Dim eventDescription As String = eventSubNode.Attributes("Description").InnerText
For Each personNode As XmlNode In eventSubNode.SelectNodes("Person")
Dim personId As String = personNode.Attributes("PersonId").InnerText
Dim personName As String = personNode.Attributes("PersonName").InnerText
Dim personAddress As String = personNode.Attributes("Address").InnerText
Next
Next
However, if you are loading all the data in the XML like this, I would recommend deserializing the XML into an EventTracker object. Or, as I said in my comment on your post, if the only purpose for reading the XML document is to transform it into another XML or HTML document, I would recommend using XSLT, instead.
If you want to test if an attribute exists, you can do something like this:
Dim attribute As XmlNode = personNode.Attributes.GetNamedItem("PersonId")
If attribute IsNot Nothing Then
Dim personId As String = attribute.InnerText
End If
However, this would be much easier with serialization since the deserialized object would simply have null properties for any elements that didn't exist.
You can use SelectSingleNode("XPath or NodeName") and loop through the Attributes.Item(index) on that node. You can also, if you know the childnode name in advance, loop through SelectSingleNode("XPath Or NodeName").SelectSingleNode("XPath or ChildName").Attributes.Item(index).
Is there any easy method for splitting text in VB.NET? (using a start and end string to grab whats in between?)
I do this all the time in JScript with the following:
<junk>
<blah>
<data>someData1</data>
<data>someData2</data>
<data>someData3</data>
</blah>
</junk>
var data = string.split('<data>')[1].split('</data>')[0];
would give me "someData1" by changing the [1] index to [2] would give me "someData2" very easy
for some reason this seems to be very difficult to achieve in VB.NET.
Here is a chunk of the actual HTML I'm dealing with:
<...malformed html>
<div style='font-size:10pt;font-family:Times;color:#000000;position:absolute;top:2731.068;left:48'>Total</div>
<div style='font-size:10pt;font-family:Times;color:#000000;position:absolute;top:2731.068;left:346.2141'>18,072.59</div>
<div style='font-size:10pt;font-family:Times;color:#000000;position:absolute;top:2731.068;left:444.3433'>100.00%</div>
<div style='font-size:10pt;font-family:Times;color:#000000;position:absolute;top:2731.068;left:567.1293'>21,687.11</div>
<div style='font-size:10pt;font-family:Times;color:#000000;position:absolute;top:2731.068;left:666.3433'>100.00%</div>
<malformed html...>
I need to find the <div>Total</div> index then grab the data between the 1st and 3rd divs after that.
Dim e = XElement.Parse(str)
Dim a = e.XPathSelectElements("./blah").Elements().ToArray()
a(0).Value 'someData1
a(1).Value 'someData2
EDIT:
To parse html try using the Html Agility Pack
I got it working, although this is some of the worse code I've ever written...
Dim sr As StreamReader
sr = New StreamReader("C:\test.html")
Dim xactHTML As String = sr.ReadToEnd
Dim left As Integer = xactHTML.IndexOf("Total</div>")
Dim chunk1 As String = xactHTML.Substring(left + 12)
Dim right As Integer = chunk1.IndexOf("<div style='position")
Dim chunk2 As String = chunk1.Substring(0, right - 1)
Dim xHTML As String = "<xml>" & chunk2 & "</xml>"
Dim e = XElement.Parse(xHTML)
Dim a = e.Elements().ToArray()
Dim damageAmmount As String = a(2).Value()