adding new child nodes to XML on each function call - asp.net

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.

Related

create Xml Document from Node

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

How to check for different root nodes efficiently

I've got an ASP.NET (VB) user control that I am going to be loading an XML document into. This document could have one of two possible root node names. I have 3 possible xsl files that will need to be prepended in the xml file through the .NET. Adding the xsl reference is not a problem but I'm running into an issue determining WHICH xsl file to add.
The first thing I need to determine, after I load the XML document is what is the root node. It can be either
<Document xmlns="urn:hl7-org:v3">
<templateId root="usetemplate_1" />
or
<Document xmlns="urn:hl7-org:v3">
<templateId root="usetemplate_2" />
or
<Record xmlns="urn:astm-org:REC">
<objectId>useobjectid</objectId>
Take note that the first two have one namespace and the third has a different namespace (not sure how to reconcile that in my brain yet either).
Each one of these options has a different xsl file to be referenced. I've got similar code in another place that I can reuse, as I said, it's just a matter of determining the right file to reference. I've got this so far:
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
m_xmld = New XmlDocument
m_xmld.Load(Me.XMLFileName)
Dim nsmgr As New XmlNamespaceManager(m_xmld.NameTable)
nsmgr.AddNamespace("x", "urn:hl7-org:v3")
m_nodelist = m_xmld.SelectNodes("x:Document/", nsmgr)
For Each m_node In m_nodelist
Next
I'm just at a loss as to what to put between the for each/next lines to determine which one from the options above or if that is even necessary and can be done more efficiently a different way.
This should work:
Dim m_xmld As New XmlDocument()
m_xmld.Load(Me.XMLFileName)
Dim nsmgr As New XmlNamespaceManager(m_xmld.NameTable)
nsmgr.AddNamespace("h", "urn:hl7-org:v3")
nsmgr.AddNamespace("a", "urn:astm-org:REC")
If m_xmld.SelectSingleNode("/h:Document/h:templateId[#root='usetemplate_1']", nsmgr) IsNot Nothing Then
' Use xsl A
ElseIf m_xmld.SelectSingleNode("/h:Document/h:templateId[#root='usetemplate_2']", nsmgr) IsNot Nothing Then
' Use xsl B
ElseIf m_xmld.SelectSingleNode("/a:Record/a:objectId", nsmgr) IsNot Nothing Then
' Use xsl C
End If
Or, if a Select Case makes more sense, you can get the value of the attribute, like this:
Dim root As XmlNode = doc.SelectSingleNode("/h:Document/h:templateId/#root", nsmgr)
If root IsNot Nothing Then
Select Case root.InnerText
Case "usetemplate_1"
' Use xsl A
Case "usetemplate_2"
' Use xsl B
End Select
ElseIf doc.SelectSingleNode("/a:Record/a:objectId", nsmgr) IsNot Nothing Then
' Use xsl C
End If
You can add as many namespaces as you want to the namespace manager. Even if the namespaces don't actually get used anywhere in the XML document, that won't be a problem. So, as you can see, you can add both potential namespaces at the same time.

Copy all elements from word doc

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()

DevExpress how to set and get tree node text and name at run time?

I am new in dev express technology. I am having a problem with devexpress XtraTreeList because i am unable to get node "NAME" and "TEXT" property.Please any one help me out through code.
One thing you need to keep in mind is that each node can be made up of multiple values. Based on the number of columns that are displayed. So, what you actually want to access is the particular column of a node in order to access or set the values for that column in the node.
For example:
TreeListColumn columnID1 = treeList1.Columns["Budget"];
// Get a cell's value in the first root node.
object cellValue1 = treeList1.Nodes[0][columnID1];
and
string columnID2 = "Budget";
// Get the display text of the focused node's cell
string cellText = treeList1.FocusedNode.GetDisplayText(columnID2);
Check out the devExpress documentation too. It's pretty helpful.
Maybe this example can help you:
Public Sub LoadTree()
TreeList1.Columns.Add().Name = "DisplayColumn"
Dim node1 = TreeList1.Nodes.Add("Father")
node1.Tag = "Father"
Dim node1_1 = TreeList1.Nodes.Add("Child Node")
node1_1.Tag = "Child Node"
Dim node1_1_1 = node1.Nodes.Add("This is a grandchild node")
node1_1_1.Tag = "Grandchild 1"
Dim node1_1_2 = node1.Nodes.Add("Another grandchild node")
node1_1_2.Tag = "Grandchild 2"
End Sub
Public Sub DisplayNodeValue(ByVal tag As String)
Dim valueToPresent = FirstTagValueInNode(TreeList1.Nodes, tag)
MsgBox(valueToPresent.ToString)
End Sub
Public Function FirstTagValueInNode(ByVal nodes As DevExpress.XtraTreeList.Nodes.TreeListNodes, ByVal tagSearch As Object)
For Each node As DevExpress.XtraTreeList.Nodes.TreeListNode In nodes
If node.Tag = tagSearch Then
Return node.GetValue(TreeList1.Columns(0))
End If
If node.Nodes.Count > 0 Then
Return FirstTagValueInNode(node.Nodes, tagSearch)
End If
Next
Return Nothing
End Function

System.InvalidOperationException: This document already has a 'DocumentElement' node

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

Resources