How to select XML node with different XML namespace? - asp.net

I have a XML document which looks like :
<stReq xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<EvalRes>
<RenDtSrc xmlns="http://fakeurl.com/somthing/facade/params">
<ContentType>application/pdf</ContentType>
<DocumentName>Name</DocumentName>
<Content>Doc Content</Content>
</RenDtSrc>
</EvalRes>
</stReq>
From a asp.net application, I am trying to check if a node <RenDtSrc> exists in a document or not. Following is the code I am using to read XML file and node element
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("D:\\Test\\Doc1.xml");
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/stReq/EvalRes/RenDtSrc");
Count of nodeList returns zero even though there are child nodes inside it.
I think its something to do with namespace manager but I can't figure it out. Any help would be appreciated.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("D:\\Test\\Doc1.xml");
var nsm = new XmlNamespaceManager(xmlDoc.NameTable);
nsm.AddNamespace("s", "http://fakeurl.com/somthing/facade/params");
XmlNodeList nodeList = xmlDoc.SelectNodes("//s:RenDtSrc", nsm);

XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("//stReq/EvalRes/node()/*");
Output:
Node [0] = {Element, Name="ContentType"}
Node [1] = {Element, Name="DocumentName"}
Node [2] = {Element, Name="Content"}

Related

Read xml embedded in aspx page

I want to read this source as xml
http://blabla/bla.aspxPageMethod=ElencoPresentiNew&idArea=0&dtRif=&mostra=T&format=xml
That returns a result like the following (straight in the browser, not as file)
I tried to use XmlDocument or Agilitypack tool, also httpwebrequest, but I get different problems. With xmldocument I get an error saying that some xml elements are missing, with the other methods I get the html source of the page but not the data.
How can I achieve what I want? Thanks
EDIT:
first xml lines from source:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Result>
<has_custom_url>false</has_custom_url>
<oggi>24.10.2019</oggi>
<utente>
<controlli196eseguiti>true</controlli196eseguiti>
<idprofiloutente>17</idprofiloutente>
<dizionario>
<u>U</u>
<e>E</e>
</dizionario>
<nominativo>super</nominativo>
<cambiopwd>1567402823277</cambiopwd>
<descrinsediamento>Insediamento principale</descrinsediamento>
EDIT 2:
Dim doc As XmlDocument = New XmlDocument()
doc.Load("http://192.168.2.49/checkandin/area.aspx?PageMethod=ElencoPresentiNew&idArea=0&dtRif=&mostra=T&format=xml")
Dim ns As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
Dim nodes As XmlNodeList = doc.SelectNodes("PresentiPerAreaCalc", ns)
Dim listaIniziale As New List(Of String)
For Each node As XmlNode In nodes
Dim record As String = node.SelectSingleNode("descrazienda").Value
listaIniziale.Add(record)
Next

adding new child nodes to XML on each function call

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.

Programmatic update of InfoPath form XML is stripping off tags

I have a C# program that is looping through all of the forms (browser enabled) in my forms library and injecting an XML node into each of them (for a newly promoted field). For some reason, when the XML is saved back to the form, the first few tags are being stripped off. Specifically, these tags are:
<?xml version="1.0"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:Contractor-DB-Form:-myXSD-2009-09-10T18-19-55" solutionVersion="1.0.1.1100" productVersion="12.0.0.0" PIVersion="1.0.0.0" href="http://echouat.rbs.us/npe/FormServerTemplates/Contractor_DB_Form.xsn"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<?mso-infoPath-file-attachment-present?>"
My code to update the XML is as follows:
private static SPListItem InsertXmlNode(SPListItem infoPathForm, string nodeToUpdateStr, string nodeToInsertStr,
string nodeInnerXmlStr, string firstNode)
{
//load form into xml document
byte[] fileBytes = infoPathForm.File.OpenBinary();
MemoryStream itemStream = new MemoryStream(fileBytes);
//Stream itemStream = infoPathForm.File.OpenBinary();
XmlDocument xmlDoc = new XmlDocument();
XmlNamespaceManager xmlNameSpaceMgr = new XmlNamespaceManager(xmlDoc.NameTable);
xmlNameSpaceMgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-10T18:19:55");
xmlDoc.Load(itemStream);
itemStream.Close();
//inject xml
XmlNode nodeToUpdate = xmlDoc.SelectSingleNode(firstNode + nodeToUpdateStr, xmlNameSpaceMgr);
//only insert if doesn't already exist
if (xmlDoc.SelectSingleNode(firstNode + nodeToUpdateStr + "/" + nodeToInsertStr, xmlNameSpaceMgr) == null)
{
updateCounter++;
XmlNode nodeToInsert = xmlDoc.CreateNode(XmlNodeType.Element, nodeToInsertStr, "http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-10T18:19:55");
nodeToInsert.InnerText = nodeInnerXmlStr;
nodeToUpdate.AppendChild(nodeToInsert);
//get binary data for updated xml
byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.DocumentElement.OuterXml);
MemoryStream newMemStream = new MemoryStream(newXmlData);
//write updated binary data to the form
infoPathForm.File.SaveBinary(newMemStream);
newMemStream.Close();
infoPathForm.File.Update();
}
return infoPathForm;
}
The addition of the new node is working properly; I can see that the new XML is properly formed. It's just that the tags get stripped off once the file is loaded from the MemoryStream into the XmlDocument object. And once these tags are missing, the forms won't open anymore in IP.
PLEASE HELP!
Thank you!
Change the line which reads:
byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.DocumentElement.OuterXml);
to read:
byte[] newXmlData = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);

Please check my XPath query

please tell me where is problem. i wrote this xpath query but its not retriveing me any node.
i want to select "HotelName" from it:-
my selector code:
Dim xmlPath As String = Server.MapPath("aa.xml")
Dim doc As XmlDocument = New XmlDocument()
doc.Load(xmlPath)
Dim nodeList As XmlNodeList = doc.DocumentElement.SelectNodes("//HotelInfo/HotelName")
For Each child As XmlNode In nodeList
Response.Write("Node Name: " + child.Name)
Response.Write("Node Value:" + child.FirstChild.Value)
Next
my xml is like this:
<?xml version="1.0" encoding="utf-8"?>
<OTA_HotelDescriptiveInfoRS xmlns="http://www.opentravel.org/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05 OTA_HotelDescriptiveInfoRS.xsd" TimeStamp="2009-12-29T06:41:55-05:00" Version="1.006" PrimaryLangID="it" EchoToken="1" Target="Test">
<Success />
<Warnings>
<Warning Code="999" Type="2"> Your request's version is earlier than our supported version. We tried to process your request in case the versions are compatible. We support version 1.006 for the OTA_HotelDescriptiveInfoRQ call.</Warning>
</Warnings>
<HotelDescriptiveContents HotelCode="112" HotelCodeContext="HCL" HotelName="Hostal Cruz Sol" HotelCityCode="335">
<HotelDescriptiveContent HotelCode="112" HotelCodeContext="HCL" HotelName="Hostal Cruz Sol" HotelCityCode="335" CurrencyCode="EUR">
<HotelInfo>
<HotelName>Hostal Cruz Sol</HotelName>
Try this:
Dim nsmgr as XmlNamespaceManager = new XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("ota", "http://www.opentravel.org/OTA/2003/05")
Dim nodeList As XmlNodeList =
doc.DocumentElement.SelectNodes("//ota:HotelInfo/ota:HotelName", nsmgr)
That xmlns added a default namespace, and you need to deal with it in your XPath expression.

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