how we can set value for xml element using XmlDocument class - c#

Is it possible to set value dynamically for any XML element using the XmlDocument class? Suppose my XML is
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<soapenv:Body>
<v9:ProcessShipmentReply xmlns:v9="http://fedex.com/ws/ship/v9">
<v9:HighestSeverity xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">SUCCESS</v9:HighestSeverity>
<v9:Notifications xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<v9:Severity>SUCCESS</v9:Severity>
<v9:Source>ship</v9:Source>
<v9:Code>0000</v9:Code>
<v9:Message>Success</v9:Message>
<v9:LocalizedMessage>Success</v9:LocalizedMessage>
</v9:Notifications>
<v9:CompletedShipmentDetail>
<v9:CompletedPackageDetails xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<v9:SequenceNumber>1</v9:SequenceNumber>
<v9:TrackingIds>
<v9:TrackingIdType>GROUND</v9:TrackingIdType>
<v9:TrackingNumber>634649515000016</v9:TrackingNumber>
</v9:TrackingIds>
<v9:Barcodes>
<v9:BinaryBarcodes>
<v9:Type>COMMON_2D</v9:Type>
<v9:Value>Wyk+HjAxHTAyMDI3ODAdODQwHTEzNx02MzQ2NDk1</v9:Value>
</v9:BinaryBarcodes>
<v9:StringBarcodes>
<v9:Type>GROUND</v9:Type>
<v9:Value>9612137634649515000016</v9:Value>
</v9:StringBarcodes>
</v9:Barcodes>
<v9:Label>
<v9:Type>OUTBOUND_LABEL</v9:Type>
<v9:ShippingDocumentDisposition>RETURNED</v9:ShippingDocumentDisposition>
<v9:Resolution>200</v9:Resolution>
<v9:CopiesToPrint>1</v9:CopiesToPrint>
<v9:Parts>
<v9:DocumentPartSequenceNumber>1</v9:DocumentPartSequenceNumber>
<v9:Image>iVBORw0KGgoAAAANSUhEUgAAAyAAAASwAQAAAAAryhMIAAAagEl</v9:Image>
</v9:Parts>
</v9:Label>
</v9:CompletedPackageDetails>
</v9:CompletedShipmentDetail>
</v9:ProcessShipmentReply>
</soapenv:Body>
How could I set value for the below element like
<v9:Severity>SUCCESS</v9:Severity>
<v9:Source>ship</v9:Source>
I know how to extract data from XML and I think it is also possible to set value for the XML element using XMLDocument class. Looking for guidance.

If you know how to select a value, then you probably know how to update one too.
XmlDocument doc = new XmlDocument();
doc.Load(...);
XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("v9", "http://fedex.com/ws/ship/v9");
XmlNode severityNode = doc.SelectSingleNode("//v9:Severity", nsMgr);
severityNode.innerText = "FAILURE";
The important thing to know is that the <v9:Severity> node has an inner text() node, so in the example above you can't use the Node.Value property. To do that you would do something like this instead:
XmlNode severityTextNode = doc.SelectSingleNode("//v9:Severity/text()", nsMgr);
severityTextNode.Value = "FAILURE";
Note the subtle differences.

Do an XPath to the superior node using the XMLDocument class and add the 2 extra nodes on the tree.

Related

Document.SelectNodes returning zero nodes. Is there anything wrong in my xml?

I have following xml. But, when I am loading it and selecting node I am getting 0 nodes. Is there anything wrong with my xml?
Code to load xml :
XmlDocument doc = new XmlDocument();
doc.LoadXml(strOfferListing);
XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("ns", "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd");
mgr.AddNamespace("root", "http://mws.amazonservices.com/schema/Products/2011-10-01");
var nodes = doc.SelectNodes("//GetMatchingProductResponse");
This is my xml file :
<?xml version="1.0" encoding="UTF-8"?>
<GetMatchingProductResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01"><GetMatchingProductResult ASIN="0470265957" status="Success"><Product><Identifiers><MarketplaceASIN><MarketplaceId>XXXXXXXXXX</MarketplaceId><ASIN>0470265957</ASIN></MarketplaceASIN></Identifiers><AttributeSets><ns2:ItemAttributes xml:lang="en-US" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd"><ns2:Author>Milton H. Erickson</ns2:Author><ns2:Author>Ernest L. Rossi</ns2:Author><ns2:Binding>Hardcover</ns2:Binding><ns2:Edition>1st</ns2:Edition><ns2:IsEligibleForTradeIn>true</ns2:IsEligibleForTradeIn><ns2:Label>Irvington Publishers</ns2:Label><ns2:Languages><ns2:Language><ns2:Name>english</ns2:Name><ns2:Type>Published</ns2:Type></ns2:Language><ns2:Language><ns2:Name>english</ns2:Name><ns2:Type>Original Language</ns2:Type></ns2:Language><ns2:Language><ns2:Name>english</ns2:Name><ns2:Type>Unknown</ns2:Type></ns2:Language></ns2:Languages><ns2:ListPrice><ns2:Amount>211.86</ns2:Amount><ns2:CurrencyCode>USD</ns2:CurrencyCode></ns2:ListPrice><ns2:Manufacturer>Irvington Publishers</ns2:Manufacturer><ns2:NumberOfItems>1</ns2:NumberOfItems><ns2:NumberOfPages>512</ns2:NumberOfPages><ns2:PackageDimensions><ns2:Height Units="inches">1.70</ns2:Height><ns2:Length Units="inches">9.40</ns2:Length><ns2:Width Units="inches">6.30</ns2:Width><ns2:Weight Units="pounds">1.85</ns2:Weight></ns2:PackageDimensions><ns2:ProductGroup>Book</ns2:ProductGroup><ns2:ProductTypeName>ABIS_BOOK</ns2:ProductTypeName><ns2:PublicationDate>1979-10-01</ns2:PublicationDate><ns2:Publisher>Irvington Publishers</ns2:Publisher><ns2:SmallImage><ns2:URL>http://ecx.images-amazon.com/images/I/51geup2R-DL._SL75_.jpg</ns2:URL><ns2:Height Units="pixels">75</ns2:Height><ns2:Width Units="pixels">56</ns2:Width></ns2:SmallImage><ns2:Studio>Irvington Publishers</ns2:Studio><ns2:Title>Hypnotherapy: An Exploratory Casebook</ns2:Title></ns2:ItemAttributes></AttributeSets><Relationships /><SalesRankings><SalesRank><ProductCategoryId>book_display_on_website</ProductCategoryId><Rank>562887</Rank></SalesRank><SalesRank><ProductCategoryId>3558816011</ProductCategoryId><Rank>63</Rank></SalesRank><SalesRank><ProductCategoryId>173514</ProductCategoryId><Rank>38091</Rank></SalesRank></SalesRankings></Product></GetMatchingProductResult></GetMatchingProductResponse>

SelectNodes Always returning the 0 count

SelectNodes always returning the 0 count even the it has the value.
<?xml version="1.0" encoding="utf-16"?>
<Configurations xmlns="DEH_Common.Schemas">
<sftpConfiguration>
<file>
<filedetails>
<fileext>csv</fileext>
<DataContentDetailId>1</DataContentDetailId>
</filedetails>
</file>
</sftpConfiguration>
</Configurations>
C# to read the nodelist....
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("//Configurations/sftpConfiguration/file");
It's because of using namespace in your xml, You should add namespace to xmlDoc and also no need to useDocumentElement` This code would be work:
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("a", "DEH_Common.Schemas");
XmlNodeList nodeList = xmlDoc.SelectNodes("//a:sftpConfiguration/a:file", nsmgr);
In your XML DocumentElement is the Configurations node, so your XPath should be sftpConfiguration/file
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("sftpConfiguration/file");
Try this:
xmlDoc.DocumentElement.SelectNodes("/Configurations[#*]/sftpConfiguration/file");

XPath does not work for selecting in XML

I have an XML document and for the life of me I cannot get data by using XPath. I've tried every sample I could find and no luck. I'm trying to extract the email address. Any thoughts?
The XML:
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hl7-org:v3" xsi:schemaLocation="urn:hl7-org:v3 CDA.xsd">
<typeId root="test1" extension="test2"/>
<id root="test3" extension="test4"/>
<code code="test5" codeSystem="test6" />
<effectiveTime value="201509171214"/>
<confidentialityCode code="N" codeSystem="test7" codeSystemName="test8" displayName="normal"/>
<languageCode code="en"/>
<recordTarget>
<Role>
<id root="000000" extension="number1"/>
<id root="11111" extension="number2"/>
<addr>
<streetAddressLine>Street</streetAddressLine>
<postalCode>12345</postalCode>
<city>City</city>
<state>STATE</state>
<country>COUNTRY</country>
</addr>
<telecom value="number" use="HP"/>
<telecom value="number" use="MC"/>
<telecom value="email#email"/>
<person>
<name>
<family>family</family>
<given>given</given>
<prefix/>
<suffix/>
</name>
<administrativeGenderCode code="C" codeSystem="code" codeSystemName="code name" displayName="c"/>
<birthTime value="N/A"/>
</person>
</Role>
</recordTarget>
</Document>
To load it:
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(STRING DATA FROM XML);
XPathNavigator foo = xmlDocument.CreateNavigator();
foo.MoveToFollowing(XPathNodeType.Element);
foo.Select("Document/recordTarget/Role");
I've also tried:
XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/Document/recordTarget/Role");
But none of this works. Everything comes back empty. Any ideas? I can't seem to navigate past the root.
I've also tried adding the namespace manager in the selects, with no luck.
XmlNamespaceManager manager = new XmlNamespaceManager(xmlDocument.NameTable);
You must add a namespace
XPathNavigator navigator = xmlDocument.CreateNavigator();
XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("ns", "urn:hl7-org:v3");
var role = navigator.Select("/ns:Document/ns:recordTarget/ns:Role", manager);
Try this:
//Create a namespacemanager to get the defaultnamespace of the xml document
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
//XPath to find the tag that the value isn't equals to number, in this case, it will
//return the <telecom value="email#email"/> element
String xpathQuery = "//role//telecom[#value!='number']";
If you are going to use XPath to get some attribute value, after the XPathNavigator foo = xmlDocument.CreateNavigator(); you should
use the SelectSingleNode method:
//from the XPathNavigator object, we call the SelectSingleNode method, to select a single
//node using the specified xpath query and then call the GetAttribute method to finally
//get the value attribute from that element
String email = foo.SelectSingleNode(xpathQuery).GetAttribute"value",nsmgr.DefaultNamespace);

Finding Correct Xpath C# [duplicate]

I'm having this XML document with namespaces and I want to extract some nodes using XPath.
Here's the document:
<ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<anyType xsi:type="Document">
<Id>5</Id>
<Title>T1</Title>
</anyType>
<anyType xsi:type="Document">
<Id>15</Id>
<Title>T15</Title>
</anyType>
</ArrayOfAnyType>
What's the XPath expression going to be if I want to extract all "anyType" elements with xsi:type="Document"?
I've tried this:
//anyType[#xsi:type="Document"]
and it doesn't work:
If you are using C# then you need to specify the namespace for the "anyType" element in your XPath:
var xml = new XmlDocument();
xml.LoadXml( "your xml" );
var names = new XmlNamespaceManager( xml.NameTable );
names.AddNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );
names.AddNamespace( "a", "http://tempuri.org/" );
var nodes = xml.SelectNodes( "//a:anyType[#xsi:type='Document']", names );
I think that
//anyType[namespace-uri() = "http://www.w3.org/2001/XMLSchema-instance"][local-name() = "type"]
Will do what you want.
This way you don't need to specify namespace:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("your xml");
XmlNode node = xmlDoc.SelectSingleNode("/*[local-name() = 'anyType']");
XmlNode nodeToImport = xmlDoc2.ImportNode(node, true);
xmlDoc2.AppendChild(nodeToImport);
Had nearly the same problem, I forgot to add the correct namespace for xsi:type
(http://www.w3.org/2001/XMLSchema-instance) was using http://www.w3.org/2001/XMLSchema
and I did never get any result - now it is working the following way:
<xsl:value-of select="/item1/item2/item3/#xsi:type"></xsl:value-of>

Cannot get XPath to work with unnamed namespace

The XML (fragment):
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetXMLResponse xmlns="http://sitecore.net/visual/">
<GetXMLResult>
<sitecore xmlns="">
<status>ok</status>
The code (fragment):
XmlNamespaceManager nsManager = new XmlNamespaceManager(template.NameTable);
nsManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsManager.PushScope();
XmlNode sitecoreRoot = template.SelectSingleNode("/soap:Envelope/soap:Body/*[namespace-uri()='http://sitecore.net/visual/' and local-name()='GetXMLResponse']", nsManager);
string status = sitecoreRoot.SelectSingleNode("/GetXMLResult/sitecore/status").Value;
sitecoreRoot element returns the correct node. However the XPath to get the status always returns null, even though the siteCoreRoot.OuterXMl property shows the element is present.
The only thing I can think of is the line:
<sitecore xmlns="">
is throwing off the XPath
TIA
XmlNamespaceManager ns = new XmlNamespaceManager(cd.NameTable);
ns.AddNamespace("sp", "http://schemas.xmlsoap.org/soap/envelope/");
ns.AddNamespace("sc", "http://sitecore.net/visual/");
XmlNode sitecoreRoot = cd.SelectSingleNode("//sp:Envelope/sp:Body/sc:GetXMLResponse/sc:GetXMLResult/sitecore/status", ns);
var status = sitecoreRoot.InnerText;
May help you?
If you just want the status node, you can try this xml library and the following XPath.
XElement root = XElement.Load(file); // or .Parse(string)
XElement status = root.XPathElement("//status");
The library handles doing the namespace for you.

Categories