Trying to create a new xml document from an existing xml node that is passed into a method. This with VB.NET. How to do ?
Private Shared Sub WriteChanges(parentNode As XmlNode, nodeName As String, m As Model.ModelBaseWithTracking)
Dim xml As New XmlDocument()
If parentNode.Name = "#document" Then
'Need code here
End If
End Sub
This is simple. You can create nodes in the XML document as following:
Private Shared Sub WriteChanges(parentNode As XmlNode, nodeName As String, m As Model.ModelBaseWithTracking)
Dim xml As New XmlDocument()
If parentNode.Name = "#document" Then
//To create root elemet
Dim root As XmlElement = xml.CreateElement("document")
xml.AppendChild(root)
//To add child node to root element
Dim child As XmlElement = xml.CreateElement("document1")
root.AppendChild(child)
child.SetAttribute("id", "1")
//Add more nodes same as shown above..
End If
End Sub
Related
been stuck for this for a while. I need to rename a SharePoint folder using ClientContext. I created a function like so:
Public Function renameFolder(_folders As ListItemCollection, _newFolderName As String) As Boolean
Try
Using _clientContext As New ClientContext(vSharepointSite)
AddHandler _clientContext.ExecutingWebRequest, AddressOf vClaimsHelper.clientContext_ExecutingWebRequest
Dim _folder = _folders(0)
_folder.Item("Title") = _newFolderName
_folder.Item("FileLeafRef") = _newFolderName
_folder.Item("DisplayName") = _newFolderName
_folder.Update()
_clientContext.ExecuteQuery()
End Using
Return True
Catch ex As Exception
Return False
End Try
End Function
This function takes a folder collection (actually I pass a collection of only 1 folder) and the new folder name. The function executes well. Inspecting the _folder after the ExecuteQuery, everything looks as expected. However nothing happens in SharePoint, meaning that the folder name remains the original name.
Any suggestions?
Best regards and....HAPPY NEW YEAR!!!!
Ariel
Make sure List Item ( _folder variable in your example) is associated with Folder object.
How to determine whether List Item is associated with a Folder object
Using ctx As New ClientContext(webUrl)
Dim list = ctx.Web.Lists.GetByTitle(listTitle)
Dim item = list.GetItemById(itemId)
ctx.Load(item.Folder)
ctx.ExecuteQuery()
Dim isFolderItem = Not item.Folder.ServerObjectIsNull.Value
End Using
How to rename Folder using SharePoint CSOM
The following example demonstrates how to rename a Folder:
Public Sub RenameFolder(folder As Folder, folderName As String)
Dim ctx = folder.Context
Dim folderItem = folder.ListItemAllFields
folderItem("FileLeafRef") = folderName
folderItem("Title") = folderName
folderItem.Update()
ctx.ExecuteQuery()
End Sub
Usage
Using ctx As New ClientContext(webUrl)
Dim folder = ctx.Web.GetFolderByServerRelativeUrl(folderUrl)
RenameFolder(folder, "Orders")
End Using
Use the BaseName field to rename the folder.
_folder.Item("BaseName") = _newFolderName
I'm trying to copy all the elements from a word doc to a new word doc. When I try to get all ChildElements I get the message "Object reference not set to an instance of an object" on this line "For Each element As OpenXmlElement In templatedoc.MainDocumentPart.Document.Body.ChildElements"
Please help
Code:
Dim containerElement = NewDocument.MainDocumentPart.Document.Descendants().FirstOrDefault()
Dim clonedElements = New List(Of OpenXmlElement)
For Each element As OpenXmlElement In templatedoc.MainDocumentPart.Document.Body.ChildElements
clonedElements.Add(element.Clone())
Next
containerElement.RemoveAllChildren()
containerElement.Append(clonedElements)
Thanks guys and girls!
Here is my final working code:
' Copy XML parts to define document
NewDocument.AddPart(templatedoc.GetPartById("rId3"), "rId3")
NewDocument.AddPart(templatedoc.GetPartById("rId2"), "rId2")
'// Add a main document part.
Dim mainPart = NewDocument.AddMainDocumentPart()
' // Add a Body
mainPart.Document = New Document(New Body())
'Copy Document XMLParts - must be in specific order
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId8"), "rId8")
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId3"), "rId3")
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId7"), "rId7")
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId2"), "rId2")
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId1"), "rId1")
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId6"), "rId6")
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId5"), "rId5")
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId4"), "rId4")
mainPart.AddPart(templatedoc.MainDocumentPart.GetPartById("rId9"), "rId9")
'// Copy text from template document
Dim containerElement = NewDocument.MainDocumentPart.Document.Descendants().FirstOrDefault()
Dim clonedElements = New List(Of OpenXmlElement)
Dim elementstocopy = templatedoc.MainDocumentPart.Document.Body.ChildElements
For Each element As OpenXmlElement In elementstocopy
clonedElements.Add(element.Clone())
Next
containerElement.RemoveAllChildren()
containerElement.Append(clonedElements)
mainPart.Document.Save()
I have an XML file and I have a function to which this XML is passed as string. I have loaded this string in Xmldocument and I need to insert few children nodes under one node. This function returns the modified XML string. I want that whenever this function is called, new child nodes are added, currently, It adds child nodes once.
Do I need to overwrite the XML file ? If so, How can I replace the node with new node ( with new child nodes added) so that It has child nodes added before the function is called again ?
My code looks something like this:
Dim doc As New XmlDocument
doc.LoadXml(applicationXml)
Dim parentNode As XmlNode = doc.GetElementsByTagName("prList").Item(0)
Dim newElement As XmlNode = doc.CreateNode(XmlNodeType.Element, "gate.util.persistence.LanguageAnalyserPersistence", Nothing)
Dim runtimeParamsElement As XmlNode = doc.CreateNode(XmlNodeType.Element, "runtimeParams", Nothing)
Dim xa As XmlAttribute = doc.CreateAttribute("class")
xa.Value = "gate.util.persistence.MapPersistence"
runtimeParamsElement.Attributes.Append(xa)
localMapElement = doc.CreateNode(XmlNodeType.Element, "localMap", Nothing)
featuresElement.AppendChild(localMapElement)
newElement.AppendChild(featuresElement)
Return doc.InnerXml
You are not showing enough code to determine the exact problem. Which node are you trying to replace? Where did featuresElement come from? Here are a few answers:
Yes you need to replace the whole file using the new document.
You don't need to replace the node with a new node. Just pass the target node to your function. The function should call appendChild() on the parent node to add a child.
When you write the document to file, example, it will have the new nodes.
I'm working on a custom menu system in asp.net that populates a horizontal menu on the fly based on which menu item is selected from the website's main menu.
This 2nd menu is populated from a custom XML file in the website's root directory.
(See http://loganyoung.wordpress.com/2010/06/03/asp-net-horizontal-submenu-from-xml/ for details).
At the time I'd written that post, it did work, but my development environment has changed and now I'm getting an error saying that the XML file can't be found.
Here's my code:
Imports System.Xml
Partial Class Site
Inherits System.Web.UI.MasterPage
Protected Sub Menu1_MenuItemClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles Menu1.MenuItemClick
Select Case e.Item.Value.ToString
Case "Team"
Dim doc As New XmlDocument
doc.Load("~/Submenus.xml")
Dim NameNodes As XmlNodeList = doc.SelectNodes("/TeamMenu/item/name")
Dim URLNodes As XmlNodeList = doc.SelectNodes("/TeamMenu/item/url")
If NameNodes.Count = URLNodes.Count Then
For i As Integer = 0 To NameNodes.Count - 1
Dim m As New MenuItem
m.Text = NameNodes.Item(i).FirstChild.InnerText
m.NavigateUrl = URLNodes.Item(i).FirstChild.InnerText
Menu2.Items.Add(m)
Next
End If
Case "Investments"
Dim doc As New XmlDocument
doc.Load("~/Submenus.xml")
Dim NameNodes As XmlNodeList = doc.SelectNodes("/InvestmentsMenu/item/name")
Dim URLNodes As XmlNodeList = doc.SelectNodes("/InvestmentsMenu/item/url")
If NameNodes.Count = URLNodes.Count Then
For i As Integer = 0 To NameNodes.Count - 1
Dim m As New MenuItem
m.Text = NameNodes.Item(i).FirstChild.InnerText
m.NavigateUrl = URLNodes.Item(i).FirstChild.InnerText
Menu2.Items.Add(m)
Next
End If
Case "Social Responsibility"
Dim doc As New XmlDocument
doc.Load("~/Submenus.xml")
Dim NameNodes As XmlNodeList = doc.SelectNodes("/InvestmentsMenu/item/name")
Dim URLNodes As XmlNodeList = doc.SelectNodes("/InvestmentsMenu/item/url")
If NameNodes.Count = URLNodes.Count Then
For i As Integer = 0 To NameNodes.Count - 1
Dim m As New MenuItem
m.Text = NameNodes.Item(i).FirstChild.InnerText
m.NavigateUrl = URLNodes.Item(i).FirstChild.InnerText
Menu2.Items.Add(m)
Next
End If
End Select
End Sub
End Class
And here's the error I'm getting:
Could not find a part of the path 'c:\windows\system32\inetsrc\~\Submenus.xml'.
Menu2 is just a completely empty <asp:Menu> control directly under the main menu on the page.
Can someone tell me what I'm doing wrong please?
Thanks in advance.
XmlDocument.Load is expecting a file path where you are providing a virtual path. Try changing it to this:
doc.Load(Page.MapPath("~/Submenus.xml"))
If you use doc.Load("~/Submenus.xml") this xml must be in your project. Otherwise you have to use server.mappath.
I have a trouble on appending new node to xmldocument (created in the memory). I have select the root node with the XmlDocument.SelectSingleNode() method, it work sometimes and in the other time it will give me "System.InvalidOperationException: This document already has a 'DocumentElement' node." error. More information, this xml document is multi level xml document.
By the way, when i try it with unit test it work fine (always), when i implement it in ASP.NET 3.5, it become weird, work sometimes and fail sometimes. Any idea, why this can help? All advise and suggestion are welcome.
Thanks.
You can select the root node of the XmlDocument using the Property "DocumentElement". Or i think you can use the Property "FirstChild" (untested).
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
XmlElement rootNode = doc.DocumentElement;
This worked for me.
xmlOriginFile = New XmlDocument()
xmlTargetFile = New XmlDocument()
xmlOriginFile.Load(readFile) //readFile is a string that hold path to xml document
xmlTargetFile.Load(writeFile) //writeFile is a string that hold path to xml document
Dim fileNav As XPathNavigator = xmlOriginFile.CreateNavigator()
Dim fileItr As XPathNodeIterator = fileNav.Select("//data")
Dim addToDestNodes As List(Of XmlNode) = New List(Of XmlNode)
While (fileItr.MoveNext())
Dim addNode As XmlNode = CType(fileItr.Current, IHasXmlNode).GetNode()
addToDestNodes.Add(addNode)
End While //loop thru nodes
If addToDestNodes.Count > 0 Then
For Each addedNode As XmlNode In addToDestNodes
Dim addTargetNode As XmlNode = xmlTargetFile.ImportNode(addedNode, True)
xmlTargetFile.DocumentElement.AppendChild(addTargetNode)
Next
End If
xmlTargetFile.Save(xmlTarget) //xmlTarget is a string that hold path to xml document
XML has a root element and you have to add new element within this root element.
XmlElement eleParent = docDestn.CreateElement("EleParent");
XmlElement eleChild = docDestn.CreateElement("Item");
eleParent.AppendChild(eleChild);
XMLNode rootNode= xmlDoc.SelectSingleNode("RootEle");
rootNode.AppendChild(eleParent);
Plps. refer the link for detail: http://navinpandit.blogspot.in/2016/12/exception-this-document-already-has.html