XDocument with multiple namespace in c# - c#

Here is my xml. i am using XDocument in C#. I want to get the "recordSetCount".
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ShowPositionOpening xmlns="http://data.usajobs.gov">
<ApplicationArea xmlns="http://www.openapplications.org/oagis/9">
<CreationDateTime>2014-12-11T04:05:41</CreationDateTime>
</ApplicationArea>
<DataArea xmlns="http://www.hr-xml.org/3">
<Show recordSetCount="6" recordSetTotal="6" recordSetCompleteIndicator="false" recordSetReferenceId="1" xmlns="http://www.openapplications.org/oagis/9">
<OriginalApplicationArea>
<CreationDateTime>2014-12-11T04:05:41</CreationDateTime>
</OriginalApplicationArea>
</Show>
I have tried like below
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
var jobCount = x.XPathSelectElement("/s:Envelope/s:Body/ShowPositionOpening/DataArea/Show/#recordSetCount", namespaceManager).Value;
but it dint work. Also tried like below
XNamespace xmlns = "http://www.openapplications.org/oagis/9";
XNamespace xmlns1 = "http://data.usajobs.gov";
XNamespace x1 = "http://www.hr-xml.org/3";
var jobCount = x.Element("ShowPositionOpening")
.Element(xmlns1 + "DataArea")
.Element(x1 + "Show")
.Attribute("recordSetTotal");
But it didn't work. What went wrong. Can any one help me?

Your data has multiple namespaces where each child is in a different namespace, you'll need to adjust your queries accordingly.
ShowPositionOpening http://data.usajobs.gov
DataArea http://www.hr-xml.org/3
Show http://www.openapplications.org/oagis/9
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
namespaceManager.AddNamespace("X", "http://data.usajobs.gov");
namespaceManager.AddNamespace("XX", "http://www.hr-xml.org/3");
namespaceManager.AddNamespace("XXX", "http://www.openapplications.org/oagis/9");
// you'll need to change this to XPathEvaluate
// since you're not evaluating to an element
var JobCount = x.XPathEvaluate("/s:Envelope/s:Body/X:ShowPositionOpening/XX:DataArea/XXX:Show/#recordSetCount", namespaceManager);
or using linq:
XNamespace n = "http://data.usajobs.gov";
XNamespace nn = "http://www.hr-xml.org/3";
XNamespace nnn = "http://www.openapplications.org/oagis/9";
var JobCount = x.Descendants(n + "ShowPositionOpening")
.Elements(nn + "DataArea")
.Elements(nnn + "Show")
.Attributes("recordSetCount")
.SingleOrDefault();

Related

XDocument get and set values in XML nodes

I have this XML
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header>
<wss:Security xmlns:wss="http://schemas.xmlsoap.org/ws/2002/12/secext">
<wss:UsernameToken>
<wss:Username>username</wss:Username>
<wss:Password>password</wss:Password>
<wss:Nonce></wss:Nonce>
<wss:Created></wss:Created>
</wss:UsernameToken>
</wss:Security>
</S:Header>
<S:Body>
<TaxRegistrationNumber>213213123</TaxRegistrationNumber>
<CompanyName>sadsadasd</CompanyName>
</S:Body>
</S:Envelope>
I want to accesses to the value of <wss:Username> and set a value in <wss:Nonce> node.
I already try 3 ways to get value of <wss:Username> on C# project:
First:
XDocument xmlFile = XDocument.Load(xmlpathfile);
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("wss", "http://schemas.xmlsoap.org/ws/2002/12/secext/");
XElement UserFinanc = xmlFile.XPathSelectElement("wss:Security/wss:UsernameToken/wss:Username", ns);
Second:
XDocument xmlFile = XDocument.Load(xmlpathfile);
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
var element = xmlFile.Descendants(wss + "Security").Descendants(wss + "UsernameToken").Where(x => x.Descendants(wss + "Username").Any(y => y.Value != "")).First().Element(wss + "UsernameToken");
if (element != null)
MessageBox.Show(element.Element(wss + "Username").Value).Value);
Third:
string grandChild = (string) (from el in xmlFile.Descendants(wss + "Username") select el).First();
MsgBox.Show(grandChild);
I always have similar errors like 'The sequence contains no elements'
Your first attempt is almost right. There are a couple things missing:
The namespace defined in code must be an exact match to the one in the xml. In your case the namespace in code has an extra trailing slash. It should be http://schemas.xmlsoap.org/ws/2002/12/secext.
The XPath expression should be //wss:Security/wss:UsernameToken/wss:Username. The leading slashes basically mean "look for this node anywhere". Alternatively, you could write out the whole path begining with <S:Envelope>. You would need to add the soap envelope namespace to your code as well.

Xml path that have multiple namespaces

I can't figure out what namespaces need to be used for following Xml (sample):
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ResponseCharge xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ResponseInfo xmlns="http://www.example.net">
<ResponseDetail>
<ResponseCode>00</ResponseCode>
<RequestIdentifier>1029034</RequestIdentifier>
<RetrievalReferenceNumber>634716660366</RetrievalReferenceNumber>
<ProcessingTime>00:03:314</ProcessingTime>
</ResponseDetail>
<ResponseTransactionDetail>
<AVSResponseCode />
<CVVResponseCode />
<AuthorizationSourceCode />
<AuthorizationNumber>004454</AuthorizationNumber>
</ResponseTransactionDetail>
<EMVResponseData />
</ResponseInfo>
</ResponseCharge>
</s:Body>
</s:Envelope>
My code looks like this atm:
XmlDocument doc = new XmlDocument();
doc.Load(responseXmlFile);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
//nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
//nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
//nsmgr.AddNamespace("", "http://www.example.net");
// getting NULL here
XmlNode node = doc.SelectSingleNode("/s:Envelope/s:Body/ResponseCharge/ResponseInfo/ResponseTransactionDetail/AuthorizationNumber", nsmgr);
I'm following this post: Namespace Manager or XsltContext needed
You need to include the namespace in your query for the elements in the http://www.example.net/ namespace.
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("ex", "http://www.example.net");
XmlNode node = doc.SelectSingleNode(
"/s:Envelope/s:Body/ResponseCharge/ex:ResponseInfo/ex:ResponseTransactionDetail/ex:AuthorizationNumber",
nsmgr);
I've arbitrarily picked ex as the prefix here. What's defined in the XmlNamespaceManager only relates to your XPath query, the prefixes used in the document aren't relevant.
Alternatively, I'd suggest you use LINQ to XML:
XNamespace ns = "http://www.example.net"
var doc = XDocument.Load(responseXmlFile);
var authNo = (int)doc.Descendants(ns + "AuthorizationNumber").Single();

Load data from XML nodes

i have this structure of data:
<?xml version="1.0" encoding="windows-1250"?>
<?xml-stylesheet type="text/xsl" href="usb71105.xsl"?>
<manas:usb xmlns:manas="http://www.manas.info/">
<manas:qr00>
<manas:verzemanas>26052708</manas:verzemanas>
<manas:verzexml>2016.03.29a</manas:verzexml>
<manas:druhtisku>U_Tisk2P/2159405/TRUE</manas:druhtisku>
</manas:qr00>
<manas:qr00>
<manas:verzemanas>26052710</manas:verzemanas>
<manas:verzexml>2016.03.30a</manas:verzexml>
<manas:druhtisku>U_Tisk2P/FALSE</manas:druhtisku>
</manas:qr00>
</manas:usb>
I need to save values of: manas:verzemanas ; manas:verzexml ;
I have this code:
XmlDocument doc = new XmlDocument();
doc.Load("d:\\83116623.XML");
foreach (XmlNode node in doc.DocumentElement)
{
string name = node.Attributes[0].ToString();
}
Have you any ideas please?
You're probably better off with XDocument. Also you need to use the namespace prefix. E.g.:
XNamespace ns = "http://www.manas.info/";
var xdoc = XDocument.Load(#"c:\temp\a\a.xml");
var verze = xdoc.Root.Elements(ns + "qr00")
.Elements(ns + "verzemanas")
.Select(e => e.Value);
verze.ToList().ForEach(v => Console.WriteLine(v));
prints
26052708
26052710

Get Element from XDocument & Edit Attribute

<GetPromotionByIdResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" MajorVersion="2" xmlns="http://fake.com/services">
<Header>
<Response ResponseCode="OK">
<RequestID>1</RequestID>
</Response>
</Header>
<Promotion PromotionId="5200" EffectiveDate="2014-10-10T00:00:00" ExpirationDate="2014-11-16T23:59:00" PromotionStatus="Active" PromotionTypeName="DefaultPromotion">
<Description TypeCode="Long" Culture="en-AU">Promotion Description</Description>
</Promotion>
</GetPromotionByIdResponse>
Im trying to extract this
<Promotion PromotionId="5200" EffectiveDate="2014-10-10T00:00:00" ExpirationDate="2014-11-16T23:59:00" PromotionStatus="Active" PromotionTypeName="DefaultPromotion">
<Description TypeCode="Long" Culture="en-AU">Promotion Description</Description>
</Promotion>
and convert the PromotionId="5200" to PromotionId="XXX"
I can extract the < Promotion > element with the below code but cant work out how to change the attribute
XNamespace xmlResponseNamespace = xmlPromotionResponse.Root.GetDefaultNamespace();
XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
nsm.AddNamespace("def", xmlResponseNamespace.ToString());
XElement xmlPromotionElement =
xmlPromotionResponse
.Descendants().SingleOrDefault(p => p.Name.LocalName == "Promotion");
You can try this way :
XNamespace ns = "http://fake.com/services";
XElement xmlPromotionElement = xmlPromotionResponse.Descendants(ns+"Promotion")
.SingleOrDefault();
xmlPromotionElement.Attribute("PromotionId").Value = "XXX";
Use simple XNamespace + local-name to reference an element in namespace. Then you can use .Attribute() method to get XAttribute from an XElement and change the attribute's value.
Try this : It returns the value of all attributes in Promotion Tag.
XNamespace ns1 = XNamespace.Get("http://fake.com/services");
var readPromotion = from a in xx.Descendants(ns1 + "Promotion")
select new
{
PromotionID = (string)a.Attribute("PromotionId"),
EffectiveDate = (string)a.Attribute("EffectiveDate"),
ExpirationDate = (string)a.Attribute("ExpirationDate"),
PromotionStatus = (string)a.Attribute("PromotionStatus"),
PromotionTypeName = (string)a.Attribute("PromotionTypeName"),
Description = (string)a.Value
};
foreach (var read in readPromotion)
{
// Read values
}

Access all nodes in xml using linq

I have xml:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<UpdateMemberHireStatus xmlns="http://tempuri.org/">
<member>
<HireAvailability>
<code>1</code>
<name>פנוי</name>
</HireAvailability>
<HireRejectReason>
<code>2</code>
<name>wow</name>
</HireRejectReason>
<IdNumber>43504349</IdNumber>
<note> </note>
</member>
</UpdateMemberHireStatus>
and I want to use LINQ to access all the nodes in the xml.
Here's what I have tried:
XNamespace ns = "tempuri.org/";
IEnumerable<HireStatus> status = from r in doc.Descendants(ns + "UpdateMemberHireStatus")
.Descendants(ns + "member")
select new HireStatus() { };
return status.ToList();
Use Descendants
var xml = XDocument.Load(XMLStream);
var allEle = xml.Descendants("UpdateMemberHireStatus"); //you can do linq now.
You can use XDocument also in the following way:
string xmlPath = "D://member.xml";
XmlDocument doc = new XmlDocument();
xdoc = XDocument.Load(xmlPath);
doc.LoadXml(xdoc.ToString());
var memberStatus= (from mem in xdoc.Descendants("member")
select mem);
foreach (XElement element in memberStatuses.ToList())
IEnumerable<XNode> nodes = element.Nodes();
var x = XElement.Load(XMLStream);
var all = x.DescendantNodes();

Categories

Resources