[VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.-VBForums
Results 1 to 13 of 13

Thread: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

  1. #1

    Thread Starter
    Frenzied Member nmadd's Avatar
    Join Date
    Jun 2007
    Location
    Colorado, U.S.A.
    Posts
    1,676

    [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    There have been some posts recently regarding creating, editing, deleting and adding to XML files. I couldn't find a post in the VB.NET CodeBank regarding XML, so I thought I'd use my basic XML skills and contribute this brief post. So here are some very basic ways of working with XML files. These snippets assume you know what XML is and that there is a System.Xml namespace available in the .NET Framework 2.0 designed to manipulate XML files. Reading through the documentation on the System.Xml namespace will greatly help!

    These are the ways that, so far, I have found to work and to be the most simple. I am still learning the System.Xml namespace. If anyone would like to comment on better ways to do something, please let me know!
    I'd be happy to update this post to help everybody.


    Creating an XML File
    Here we'll use the XmlWriter to create a new XML file. This part of working with XML files is fairly straightforward and easy. Here are the steps:
    • Create an XmlWriter
      • This class does just what it sounds like it does. It is a fast, forward-only way to write XML files.
      • Prepare the settings for the writer. In this case, only choosing to indent each element.
    • Write a declaration
      • In the basic form that we are using it, the declaration specifies which version of XML we are using and how it is encoded.
    • Write a comment
    • Write the root element
      • Each XML file can have only one root element. In our case it is the "People" element.
    • Write elements and attributes that contain information about our "Person."
      • Each person elements contain elements that describe that person in greater detail.
      • Each person contains an attribute called "ID" that will help us easier identify the person later.

    VB.NET Code:
    1. ' Set up our XmlWriter settings.
    2. Dim settings as new XmlWriterSettings()
    3. settings.Indent = True
    4.  
    5. ' Initialize the XmlWriter.
    6. Dim XmlWrt As XmlWriter = XmlWriter.Create("C:\XmlTest.xml", settings)
    7.  
    8. With XmlWrt
    9.     ' Write the Xml declaration.
    10.     .WriteStartDocument()
    11.     ' Write a comment.
    12.     .WriteComment("Xml example.")
    13.  
    14.     ' Write the root element.
    15.     .WriteStartElement("People")
    16.  
    17.     ' Start our first person.
    18.     .WriteStartElement("Person")
    19.     ' Give this person the attribute ID of 1.
    20.     .WriteAttributeString("ID", "1")
    21.  
    22.     ' The person nodes.
    23.     .WriteStartElement("Name")
    24.     .WriteString("Bob")
    25.     .WriteEndElement()
    26.  
    27.     .WriteStartElement("Age")
    28.     .WriteString("28")
    29.     .WriteEndElement()
    30.  
    31.     .WriteStartElement("Weight")
    32.     .WriteString("180")
    33.     .WriteEndElement()
    34.     ' The end of this person.
    35.     .WriteEndElement()
    36.  
    37.     ' Next person.
    38.     .WriteStartElement("Person")
    39.     .WriteAttributeString("ID", "2")
    40.  
    41.     .WriteStartElement("Name")
    42.     .WriteString("Julie")
    43.     .WriteEndElement()
    44.  
    45.     .WriteStartElement("Age")
    46.     .WriteString("34")
    47.     .WriteEndElement()
    48.  
    49.     .WriteStartElement("Weight")
    50.     .WriteString("125")
    51.     ' The end of this person.
    52.     .WriteEndElement()
    53.     ' The end of People.
    54.     .WriteEndElement()
    55.  
    56.     ' Close the XmlTextWriter.
    57.     .WriteEndDocument()
    58.     .Close()
    59. End With


    Edit an XML File
    Now that we have an XML file, we can edit it. Bob has turned a year older so we need to change his age. With the XmlDocument class we can get this done.
    • Find Bob with his attribute ID of 1
      • It is very easy to find an individual person using their attribute called "ID" since we created this in our first step.
      • We are using the XPath to find the person with the correct ID.
        • The XPath is a language used to easily traverse through an XML files elements.
    • Change the nodes we want
      • Since we have located Bob's node we can edit any of his child nodes or details. In this case we will edit his second child node (index of 1): his age.
    • Save the document
      • Clearly this is an important point, but it seems to be missed quite often. Don't forget to save!

    VB.NET Code:
    1. ' Load the XmlDocument.
    2. Dim xd As New XmlDocument()
    3. xd.Load("C:\XmlTest.xml")
    4.  
    5. ' Find the node where the Person's attribute ID is 1 using its XPath.
    6. Dim nod As XmlNode = xd.SelectSingleNode("/People/Person[@ID='1']")
    7. If nod IsNot Nothing Then
    8.     ' Since we found Bob's node now we can
    9.     ' change the InnerText of his age node.
    10.     nod.ChildNodes(1).InnerText = "29"
    11. Else
    12.     ' Where did Bob go?
    13.     MessageBox.Show("Couldn't find Bob.", "Where's Bob?", MessageBoxButtons.OK, _
    14.         MessageBoxIcon.Information)
    15. End If
    16.  
    17. ' Save the Xml.
    18. xd.Save("C:\XmlTest.xml")


    Add to an XML File
    There are certainly different approaches to appending elements to an XML file. This is the one that I found easiest to use; particularly when adding an entire Person in our case.
    • Create a string containing the information about the person that we want to add to our XML file
      • At the moment this is, of course, just a string. However, it does hold the information that we want to add to our XML file.
      • Though the XML will look nice if you view it in a browser no matter how it looks as a regular text file, for the sake of keeping it looking nice when viewed in Notepad, the string is formatted as such.
    • Load our file again
    • Create a XmlDocumentFragment
      • This is, again, just what it sounds like. This is a lightweight document fragment that is very useful for inserting nodes into an XML file.
      • Next we set the fragment's InnerXml to our string.
    • Append that fragment to our file
      • Now that we have the node setup we can append this to the end of our XmlDocument.
        • Notice that we get the XML file's root with the DocumentElement property. We don't want to append this outside of the root.
    • Save the document
      • Don't forget to save!

    VB.NET Code:
    1. ' Create our string that holds our new Person information.
    2. Dim cr as String = Environment.Newline
    3. Dim newPerson As String = _
    4.     "<Person ID='3'>" & cr & _
    5.     "    <Name>Tommy</Name>" & cr & _
    6.     "    <Age>62</Age>" & cr & _
    7.     "    <Weight>190</Weight>" & cr & _
    8.     "  </Person>"
    9.  
    10. ' Load the XmlDocument.
    11. Dim xd As New XmlDocument()
    12. xd.Load("C:\XmlTest.xml")
    13.  
    14. ' Create a new XmlDocumentFragment for our document.
    15. Dim docFrag As XmlDocumentFragment = xd.CreateDocumentFragment()
    16. ' The Xml for this fragment is our newPerson string.
    17. docFrag.InnerXml = newPerson
    18. ' The root element of our file is found using
    19. ' the DocumentElement property of the XmlDocument.
    20. Dim root As XmlNode = xd.DocumentElement
    21. ' Append our new Person to the root element.
    22. root.AppendChild(docFrag)
    23.  
    24. ' Save the Xml.
    25. xd.Save("C:\XmlTest.xml")


    Delete an XML Node
    We don't need Bob in our list of People any longer so we can now delete him. You alrealdy found him when we edited him, so we just need to change the code so we delete him instead. Easy!
    • Load the XmlDocument once again
    • Find his node again by using the correct XPath
      • You've done this before so this is no problem!
    • Delete all of his information
      • We have Bob's node. We then get his parent to remove Bob's node and all details using the RemoveChild method.
    • Save the document
      • That's right. Don't forget to save!

    VB.NET Code:
    1. ' Load the XmlDocument.
    2. Dim xd As New XmlDocument()
    3. xd.Load("C:\XmlTest.xml")
    4.  
    5. ' Find Bob's node with the attribute ID of 1
    6. ' using the XPath again.
    7. Dim nod As XmlNode = xd.SelectSingleNode("/People/Person[@ID='1']")
    8. If nod IsNot Nothing Then
    9.     ' Since we found Bob's node, we will remove
    10.     ' it and all of his information.
    11.     nod.ParentNode.RemoveChild(nod)
    12. Else
    13.     ' Where's Bob?
    14.     MessageBox.Show("Couldn't find Bob.", "Where's Bob?", MessageBoxButtons.OK, _
    15.         MessageBoxIcon.Information)
    16. End If
    17.  
    18. ' Save the Xml.
    19. xd.Save("C:\XmlTest.xml")

    Well, that's it for now. There will be more to come on XML. I can't get enough!
    I hope that these basics have helped you begin your journey into VB.NET and XML. You can also find a small application using these snippets attached. Good luck!
    Attached Files Attached Files
    Last edited by nmadd; Jul 16th, 2007 at 04:22 PM. Reason: Updated formatting & some code. Changed title.

  2. #2

    Thread Starter
    Frenzied Member nmadd's Avatar
    Join Date
    Jun 2007
    Location
    Colorado, U.S.A.
    Posts
    1,676

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Merge Two XML Files
    Let's say that you have two XML files that you would like to combine into one. So how do you "merge" two XML files? Well, you can read from one and by using the ImportNode method, append to the other.
    • Setup and load the two XmlDocuments
    • Loop through all of the nodes in the "from" document
      • All of the nodes inside of the root that is.
    • Import each node to the "to" document
    • Append each node to the "to" document
    • Save!

    VB.NET Code:
    1. ' The XmlDocument that we want to merge from.
    2. Dim xdFrom As New XmlDocument()
    3. xdFrom.Load("C:\XmlTest2.xml")
    4.  
    5. ' The XMLDocument that we want to merge to.
    6. Dim xdTo As New XmlDocument()
    7. xdTo.Load("C:\XmlTest.xml")
    8.  
    9. ' Loop through all of the nodes in the "from" document.
    10. ' We don't want to copy the root node in this instance.
    11. For Each nod As XmlNode In xdFrom.DocumentElement.ChildNodes
    12.     ' Import the node to our "to" document.
    13.     Dim tmpNod As XmlNode = xdTo.ImportNode(nod, True)
    14.     ' Append this temporary node to the end of the "to" document
    15.     ' but inside the root element.
    16.     xdTo.DocumentElement.AppendChild(tmpNod)
    17. Next nod
    18.  
    19. ' Save the "to" document with it's newly appended nodes.
    20. xdTo.Save("C:\XmlTest.xml")

    That's it! Your original XML file now contains all the nodes from the "from" file as well. The attached file in post #1 has been updated.

  3. #3
    New Member
    Join Date
    Aug 2007
    Posts
    4

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Hiya, I read your post which was really helpful!!

    I do have a problem I was wondering whether you could help me with?

    I am trying to read the content.xml of an openoffice document and want to find out the xPath to a textbox in a frame within the document which contains the text "mytextbox1"....

    Code:
    'to unzip and read content.xml of an opendocument text file
            Dim objTextDocument As New AODL.Document.TextDocuments.TextDocument
    
    'load opendocument text file
            objTextDocument.Load("C:\Users\Lynwen\Documents\textbox1.odt") 
    
    'access the textbox in content.xml 
           Dim nod As XmlNode = objTextDocument.XmlDoc.SelectSingleNode("
    office:document-content/office:body/office:text/text:p/draw:frame/draw:text-box/text:p[@text='mytextbox']")
    I have no idea how to find the xpath to the textbox... here is the xml file

    Code:
    <?xml version="1.0" encoding="UTF-8" ?> 
    - <office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.0">
      <office:scripts /> 
    - <office:font-face-decls>
      <style:font-face style:name="Tahoma1" svg:font-family="Tahoma" /> 
      <style:font-face style:name="Times New Roman" svg:font-family="'Times New Roman'" style:font-family-generic="roman" style:font-pitch="variable" /> 
      <style:font-face style:name="Arial" svg:font-family="Arial" style:font-family-generic="swiss" style:font-pitch="variable" /> 
      <style:font-face style:name="Arial Unicode MS" svg:font-family="'Arial Unicode MS'" style:font-family-generic="system" style:font-pitch="variable" /> 
      <style:font-face style:name="MS Mincho" svg:font-family="'MS Mincho'" style:font-family-generic="system" style:font-pitch="variable" /> 
      <style:font-face style:name="Tahoma" svg:font-family="Tahoma" style:font-family-generic="system" style:font-pitch="variable" /> 
      </office:font-face-decls>
    - <office:automatic-styles>
    - <style:style style:name="fr1" style:family="graphic" style:parent-style-name="Frame">
      <style:graphic-properties style:vertical-pos="from-top" style:vertical-rel="paragraph" style:horizontal-pos="from-left" style:horizontal-rel="paragraph" style:writing-mode="lr-tb" /> 
      </style:style>
      </office:automatic-styles>
    - <office:body>
    - <office:text>
      <office:forms form:automatic-focus="false" form:apply-design-mode="false" /> 
    - <text:sequence-decls>
      <text:sequence-decl text:display-outline-level="0" text:name="Illustration" /> 
      <text:sequence-decl text:display-outline-level="0" text:name="Table" /> 
      <text:sequence-decl text:display-outline-level="0" text:name="Text" /> 
      <text:sequence-decl text:display-outline-level="0" text:name="Drawing" /> 
      </text:sequence-decls>
    - <text:p text:style-name="Standard">
    - <draw:frame draw:style-name="fr1" draw:name="Frame1" text:anchor-type="paragraph" svg:x="3.466cm" svg:y="0.854cm" svg:width="9.678cm" draw:z-index="0">
    - <draw:text-box fo:min-height="3.545cm">
      <text:p text:style-name="Frame_20_contents">mytextbox1</text:p> 
      </draw:text-box>
      </draw:frame>
      </text:p>
      </office:text>
      </office:body>
      </office:document-content>

    Any kind of help would be much appreciated!! Thanks in advanced

    After I have the xpath to the textbox then i want to change the text to say something else... which should be okay once i get this part working?

  4. #4

    Thread Starter
    Frenzied Member nmadd's Avatar
    Join Date
    Jun 2007
    Location
    Colorado, U.S.A.
    Posts
    1,676

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Howdy,
    The namespaces in your XML make it a little more difficult, but thanks to help from the .NET XML namespace, not much.

    All you should need to do is add the appropriate namespace to your XmlDocument's SelectSingleNode method. There is on overload of this method that will accept a XmlNameSpaceManager.
    VB.NET Code:
    1. Dim xd As New XmlDocument()
    2. xd.Load("c:\sample.xml")
    3.  
    4. Dim xNM As New XmlNamespaceManager(xd.NameTable)
    5. ' Add the text namespace to your manager and then include it in the method below.
    6. xNM.AddNamespace("text", "urn:oasis:names:tc:opendocument:xmlns:text:1.0")
    7. ' The // is the recursive descendant operator for XPath
    8. Dim nod As XmlNode = xd.SelectSingleNode("//text:p", xNM)
    9. ' Got your node so now you can change the InnerText.
    10. If nod IsNot Nothing Then
    11.     nod.InnerText = "my NEW TextBox inner text"
    12. End If
    13. ' Save!
    14. xd.Save("c:\sample.xml")

    Google 'xpath namespace' and you'll find some good, in depth information on this. Good luck!

  5. #5
    New Member
    Join Date
    Aug 2007
    Posts
    4

    Unhappy Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Hi! Thanks, I'm beginning to get a better understanding now...

    I do still have a problem however, this is my code so far

    Code:
            
            Dim xd As New XmlDocument
    
            xd.Load("..\debug\aodlread\content.xml")
    
            Dim xNM As New XmlNamespaceManager(xd.NameTable)
    
            xNM.AddNamespace("draw", "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0")
    
            Dim nod As XmlNode = xd.SelectSingleNode("//draw:frame[@name='Frame1']", xNM)
    
            If nod IsNot Nothing Then
    
                MessageBox.Show("found")
    
            Else
                MessageBox.Show("not found")
    
            End If

    The location to the xml file is correct, and the name space for drawing should be too... I cant understand why it keeps saying not found, when it should find a frame called Frame1

    Here's the xml

    Code:
    <office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.0">
      <office:scripts /> 
    - <office:font-face-decls>
      <style:font-face style:name="Tahoma1" svg:font-family="Tahoma" /> 
      <style:font-face style:name="Times New Roman" svg:font-family="'Times New Roman'" style:font-family-generic="roman" style:font-pitch="variable" /> 
      <style:font-face style:name="Arial" svg:font-family="Arial" style:font-family-generic="swiss" style:font-pitch="variable" /> 
      <style:font-face style:name="Arial Unicode MS" svg:font-family="'Arial Unicode MS'" style:font-family-generic="system" style:font-pitch="variable" /> 
      <style:font-face style:name="MS Mincho" svg:font-family="'MS Mincho'" style:font-family-generic="system" style:font-pitch="variable" /> 
      <style:font-face style:name="Tahoma" svg:font-family="Tahoma" style:font-family-generic="system" style:font-pitch="variable" /> 
      </office:font-face-decls>
    - <office:automatic-styles>
    - <style:style style:name="fr1" style:family="graphic" style:parent-style-name="Frame">
      <style:graphic-properties style:vertical-pos="from-top" style:vertical-rel="paragraph" style:horizontal-pos="from-left" style:horizontal-rel="paragraph" style:writing-mode="lr-tb" /> 
      </style:style>
      </office:automatic-styles>
    - <office:body>
    - <office:text>
      <office:forms form:automatic-focus="false" form:apply-design-mode="false" /> 
    - <text:sequence-decls>
      <text:sequence-decl text:display-outline-level="0" text:name="Illustration" /> 
      <text:sequence-decl text:display-outline-level="0" text:name="Table" /> 
      <text:sequence-decl text:display-outline-level="0" text:name="Text" /> 
      <text:sequence-decl text:display-outline-level="0" text:name="Drawing" /> 
      </text:sequence-decls>
    - <text:p text:style-name="Standard">
    - <draw:frame draw:style-name="fr1" draw:name="Frame1" text:anchor-type="paragraph" svg:x="3.466cm" svg:y="0.854cm" svg:width="9.678cm" draw:z-index="0">
    - <draw:text-box fo:min-height="3.545cm">
      <text:p text:style-name="Frame_20_contents">mytextbox1</text:p> 
      </draw:text-box>
      </draw:frame>
      </text:p>
      </office:text>
      </office:body>
      </office:document-content>
    So I took the namespace for draw, being: xmlns:draw="urnasis:names:tcpendocument:xmlns:drawing:1.0" for the namespace with prefix "draw". Then wanted to access the frame within the draw, hence //draw:frame then wanted to find Frame1 hence [@name='Frame1'], which according to the xml file should be okay? but I'm still getting nod=nothing

  6. #6
    New Member
    Join Date
    Aug 2007
    Posts
    4

    Thumbs up Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Problem solved, I was looking in the wrong place!!!


    Here is my solution..

    Code:
            Dim objTextDocument As New AODL.Document.TextDocuments.TextDocument
    
            Dim txtTitle As String = "new title inserted!"
            Dim txtImage As String = "new image inserted!"
            Dim txtBarcode As String = "new barcode inserted!"
            Dim txtPrice As String = "new price inserted!"
    
            Dim node As Xml.XmlNode
            Dim xd As New Xml.XmlDocument
    
    
            objTextDocument.Load("C:\Users\Lynwen\Documents\textbox1.odt")
    
            xd.Load("..\debug\aodlread\content.xml")
    
            Dim xNM As New XmlNamespaceManager(xd.NameTable)
    
            xNM.AddNamespace("draw", "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0")
    
            Dim nodeList As XmlNodeList = xd.SelectNodes("//draw:frame", xNM)
    
            If nodeList IsNot Nothing Then
    
                For Each node In nodeList
    
                    MessageBox.Show(node.InnerText)
                    Select Case node.InnerText
    
                        Case "title"
                            node.InnerText = txtTitle
    
                        Case "image"
                            node.InnerText = txtImage
    
                        Case "barcode"
                            node.InnerText = txtBarcode
    
                        Case "price"
                            node.InnerText = txtPrice
    
                    End Select
    
                Next
    
                xd.Save("c:\Users\Lynwen\Documents\content.xml")
    
    
    
            Else
                MessageBox.Show("not found")
    
            End If
    I just need to find out how to save it as an open document text (.odt) now!!


    Many thanks, your posts have been fab

  7. #7
    Lively Member RibbonFan's Avatar
    Join Date
    Aug 2007
    Location
    England
    Posts
    69

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Have you tried the ODFFormsGenerator example which comes with AODL, from there you can try and convert the C# code to VB or:

    Below is my code which will save the contents of a textbox or richtextbox into an ODT file, however it does require a SaveFileDialog (the txtbox or rchtxtbox is called txtOutput):

    Code:
            SaveFileDialog1.Title = "Save a Word Document"
            SaveFileDialog1.DefaultExt = "sfu"
            SaveFileDialog1.Filter = "Spoof Factory ULTIMATE Documents (Beta)|*.sfu|OpenDocument Text Files(*.odt)|*.odt"
    
    
            If SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                textDocument.[New]()
                Dim p1 As Paragraph = New Paragraph(textDocument)
            'Displays the text enetered into the txtOutput control in OpenOffice.org
               p1.TextContent.Add(New SimpleText(textDocument, txtOutput.Text))
    
                Dim p2 As Paragraph = New Paragraph(textDocument)
    
                Dim fMain As ODFForm = textDocument.AddNewForm("mainform")
    
                Dim frame As ODFFrame = New ODFFrame(fMain, p2.Content, "frame", "5mm", "5mm", "9cm", "5cm")
                frame.Label = "Form"
                frame.AnchorType = AnchorType.Paragraph
    
                Dim ft_addinfo As ODFFixedText = New ODFFixedText(fMain, p2.Content, "ft_addinfo", "45mm", "10mm", "45mm", "4mm")
                ft_addinfo.Label = "Additional information"
    
                Dim addinfo As ODFTextArea = New ODFTextArea(fMain, p2.Content, "addinfo", "45mm", "14mm", "45mm", "25mm")
                addinfo.CurrentValue = txtOutput.Text
                addinfo.AnchorType = AnchorType.Paragraph
                addinfo.Properties.Add(New SingleFormProperty(textDocument, PropertyValueType.Boolean, "MultiLine", "true"))
    
    
    
                textDocument.Content.Add(p1)
                textDocument.Content.Add(p2)
    
                textDocument.SaveTo(SaveFileDialog1.FileName)
                lastOpenedFile = SaveFileDialog1.FileName
            End If
    End Sub
    I hope it helps!

  8. #8
    Lively Member RibbonFan's Avatar
    Join Date
    Aug 2007
    Location
    England
    Posts
    69

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Sorry about the Spoof Factory ULTIMATE document filter (it was from an old project which i made ages ago!)

  9. #9
    Hyperactive Member Cyb3rH4Xter's Avatar
    Join Date
    May 2009
    Location
    Sweden
    Posts
    449

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Hello! This is really a great example you have given but i am having problems with the add to xml thing.

    Here's my code:

    Code:
                    ' Create our string that holds our new Movie Info
    
                    Dim cr As String = Environment.NewLine
    
                    Dim newMovie As String = _
                        "<Moviename xmlns=" + name + ">" & cr & _
                        "    <Directory>" + dirname + "</Directory>" & cr & _
                        "    <Bitrate>BitrateHere</Bitrate>" & cr & _
                        "  </MovieName>"
    
                    ' Load the XmlDocument.
                    Dim xd As New XmlDocument()
    
                    xd.Load("data.xml")
    
                    ' Create a new XmlDocumentFragment for our document.
                    Dim docFrag As XmlDocumentFragment = xd.CreateDocumentFragment()
    
                    ' The Xml for this fragment is our newPerson string.
                    docFrag.InnerXml = newMovie
    
                    ' The root element of our file is found using
                    ' the DocumentElement property of the XmlDocument.
                    Dim root As XmlNode = xd.DocumentElement
    
                    ' Append our new Person to the root element.
                    root.AppendChild(docFrag)
    
                    ' Save the Xml.
                    xd.Save("data.xml")
    Where name and dirname is a movie name and a directory name that the user has chosen from a openfiledialog.

    It hungs up at the docfrag.innerxml line throwing this:

    'IntoTheBlue.mp4' is an unexpected token. The expected token is '"' or '''. Line 1, position 18.

    So, what to do to solve it?

    Here's the xml file to:

    <?xml version="1.0" encoding="utf-8"?>
    <Movies>
    <Moviename xmlns="IntoTheBlue.mp4">
    <Directory>c:\Users\Admin\Music\iTunes\iTunes Music\Movies\IntoTheBlue.mp4</Directory>
    <Bitrate>BitrateHere</Bitrate>
    </Moviename>
    </Movies>

  10. #10
    New Member
    Join Date
    Mar 2008
    Posts
    2

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Try something like:

    Code:
            
    Dim newMovie As String = _
    "<MovieName xmlns='" + name + "'>" & cr & _
    "    <Directory>" + dirname + "</Directory>" & cr & _
                        "    <Bitrate>BitrateHere</Bitrate>" & cr & _
                        "  </MovieName>"
    Just a matter of '

  11. #11
    Hyperactive Member Cyb3rH4Xter's Avatar
    Join Date
    May 2009
    Location
    Sweden
    Posts
    449

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    thx, now it works.

  12. #12
    Junior Member
    Join Date
    Feb 2012
    Posts
    26

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    With this code you have nmadd, you have added the new people within the code.

    Is it possible to use the same code, but add the new person via a textbox on a form.

    For example you have:
    Dim newPerson As String = _
    "<Person ID='3'>" & cr & _
    " <Name>Tommy</Name>" & cr & _
    " <Age>62</Age>" & cr & _
    " <Weight>190</Weight>" & cr & _
    " </Person>"

    Instead could you not use Dim newPerson as String = _ "PersonIDTextBox.Text", "NameTextBox.Text", "AgeTextBox.Text", "WeightTextBox.Text"

    Would this work?

  13. #13
    Member
    Join Date
    Oct 2011
    Posts
    50

    Re: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    Great Post .... Thank You Sir .

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.