This is mycode. I want to get elements in string xml but i didn't. Please help me.
$
string xml = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><GetCustomerInfoResponse xmlns='http://tempuri.org/'><GetCustomerInfoResult xmlns:a='http://schemas.datacontract.org/2004/07/PaymentGatewayEVNSPC' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'><a:Address>137 Phường Tân Xuyên</a:Address><a:Bills><a:BillInfo><a:Amount>1516682</a:Amount><a:BillCode>170810TD</a:BillCode><a:DenNgay i:nil='true'></a:DenNgay><a:HoaDonID>33045487</a:HoaDonID><a:Month>8</a:Month><a:SoHo>0</a:SoHo><a:TuNgay i:nil='true'></a:TuNgay><a:TyLeGia i:nil='true'></a:TyLeGia><a:Year>2017</a:Year></a:BillInfo><a:BillInfo><a:Amount>89000</a:Amount><a:BillCode>170810DC</a:BillCode><a:DenNgay i:nil='true'></a:DenNgay><a:HoaDonID>33045487</a:HoaDonID><a:Month>8</a:Month><a:SoHo>0</a:SoHo><a:TuNgay i:nil='true'></a:TuNgay><a:TyLeGia i:nil='true'></a:TyLeGia><a:Year>2017</a:Year></a:BillInfo><a:BillInfo><a:Amount>148028</a:Amount><a:BillCode>170810VC</a:BillCode><a:DenNgay i:nil='true'></a:DenNgay><a:HoaDonID>33045488</a:HoaDonID><a:Month>8</a:Month><a:SoHo>0</a:SoHo><a:TuNgay i:nil='true'></a:TuNgay><a:TyLeGia i:nil='true'></a:TyLeGia><a:Year>2017</a:Year></a:BillInfo></a:Bills><a:CustomerCode>PB14010040801</a:CustomerCode><a:DanhSo>44900L36</a:DanhSo><a:MaSoThue></a:MaSoThue><a:MaTram></a:MaTram><a:Name>Cơ Sở Mộc Thành Tài</a:Name><a:NganhNghe></a:NganhNghe><a:PhienGCS></a:PhienGCS><a:Session></a:Session><a:SoCongTo>14226305</a:SoCongTo><a:SoGhiChiSo>A1010D001</a:SoGhiChiSo></GetCustomerInfoResult></GetCustomerInfoResponse></s:Body></s:Envelope>";
window.jQuery
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var ns = new XmlNamespaceManager(new NameTable());
// XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
// ns.AddNamespace("xmlns","'http://tempuri.org/'");
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/PaymentGatewayEVNSPC");
ns.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");
string xpath = "s:Envelope/s:Body/GetCustomerInfoResponse/GetCustomerInfoResult";
// string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath,ns);
;
foreach (XmlNode childrenNode in nodes)
{
Console.Write(childrenNode.SelectSingleNode("a:Address",ns).InnerXml);
Console.Write("\n");
}
Unfortunately, in a namespaced document, you can't use XPath with the default namespace. See this answer for more info.
This works:
var ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/PaymentGatewayEVNSPC");
ns.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");
//Add a prefix for the default namespace for GetCustomerInfoResponse and GeteCustomerInforResult
ns.AddNamespace("t","http://tempuri.org/");
string xpath = "s:Envelope/s:Body/t:GetCustomerInfoResponse/t:GetCustomerInfoResult";
var nodes = xmlDoc.SelectNodes(xpath, ns);
foreach (XmlNode childrenNode in nodes)
{
Console.Write(childrenNode.SelectSingleNode("a:Address", ns).InnerXml);
Console.Write("\n");
}
Related
I'm trying to read arrays in an XML, but my code does not return results
XML :
<ArrayOfProductoModel
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/WebApi.Models">
<ProductoModel>
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>
<ProductoModel>
<descripcion>descripcion 3</descripcion>
<fecha_registro>2016-08-02</fecha_registro>
<id_producto>3</id_producto>
<id_proveedor>3</id_proveedor>
<nombre_producto>producto 3</nombre_producto>
<precio>500</precio>
</ProductoModel>
</ArrayOfProductoModel>
Code :
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(content);
XmlNodeList nodelist = xDoc.SelectNodes("ArrayOfProductoModel/ProductoModel");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
As I can read the array?
The problem is the imported namespace. You can ignore the namespace as explained here:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(content);
XmlNodeList nodelist = xDoc.DocumentElement.SelectNodes("*[local-name()='ProductoModel']");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("*[local-name()='descripcion']").InnerText);
}
Alternatively you can use an XmlNamespaceManager as explained here:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(content);
XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
manager.AddNamespace("MYNS", "http://schemas.datacontract.org/2004/07/WebApi.Models");
XmlNodeList nodelist = xDoc.DocumentElement.SelectNodes("MYNS:ProductoModel", manager);
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("MYNS:descripcion", manager).InnerText);
}
Another solution is to use Linq to XML
var xml = #"<ArrayOfProductoModel
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""
xmlns=""http://schemas.datacontract.org/2004/07/WebApi.Models"">
<ProductoModel>
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>
<ProductoModel>
<descripcion>descripcion 3</descripcion>
<fecha_registro>2016-08-02</fecha_registro>
<id_producto>3</id_producto>
<id_proveedor>3</id_proveedor>
<nombre_producto>producto 3</nombre_producto>
<precio>500</precio>
</ProductoModel>
</ArrayOfProductoModel>";
var xDoc = XDocument.Parse(xml);
var ns = xDoc.Root.Name.Namespace;
var nodelist = xDoc.Element(ns + "ArrayOfProductoModel").Elements(ns + "ProductoModel");
foreach (var node in nodelist)
{
MessageBox.Show(node.Element(ns + "descripcion").Value);
}
Don't forget to put namespace in front of local name.
At first, I think problem in
xDoc.LoadXml(content);
You try:
xDoc.Load(filePathXml);
Second, I think problem in
XmlNodeList nodelist = xDoc.SelectNodes("ArrayOfProductoModel/ProductoModel");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
You try:
XmlNode rootNode = doc.SelectSingleNode(#"/ArrayOfProductoModel");
var listProductModel = rootNode.SelectNodes(#"ProductoModel");
foreach (XmlNode node in listProductModel)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
I want an xml output as under
<ExtendedData xmlns:section="http://svr:1245/contact/kml/section.xsd">
<section:secid>svr_01</section:secid>
<section:name>test</unit:name>
</ExtendedData>
How can I achieve this? My code is as below but the output is not correct
var attribute = xDoc.CreateAttribute("section","secid","http://svr:1245/contact/kml/section.xsd");
XmlElement elementExtendedData = xDoc.CreateElement("ExtendedData");
elementPlacemark.AppendChild(elementExtendedData);
var elementSectionid = xDoc.CreateElement("section", "secid");
attribute.InnerText = UniqueID;
elementSectionid.Attributes.Append(attribute);
elementExtendedData.AppendChild(elementSectionid);
First, create the ElementData element add add the namespace prefix xmlns:section. Then add your element with the correct prefix and namespace.
var extendedData = xDoc.CreateElement("ExtendedData");
extendedData.SetAttribute("xmlns:section", "http://svr:1245/contact/kml/section.xsd");
elementPlacemark.AppendChild(extendedData);
var secId = xDoc.CreateElement("section", "secid", "http://svr:1245/contact/kml/section.xsd");
secId.InnerText = "svr_01";
extendedData.AppendChild(secId);
If you have the option, I'd suggest using LINQ to XML instead, it's much nicer to work with:
XNamespace ns = "http://svr:1245/contact/kml/section.xsd";
var element = new XElement("ExtendedData",
new XAttribute(XNamespace.Xmlns + "section", ns),
new XElement(ns + "secid", "svr_01")
);
doc = new XmlDocument();
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
XmlNode root = doc.DocumentElement;
doc.InsertBefore(xmlDeclaration, root);
string url2 = "http://www.w3.org/2000/09/xmldsig#"; //ds
XmlNode element1 = doc.CreateElement(NodoRaiz, "Facturae", "http://www.facturae.es/Facturae/2014/v3.2.1/Facturae");
XmlAttribute attr = doc.CreateAttribute("xmlns:ds");
attr.Value = url2;
element1.Attributes.Append(attr);
doc.AppendChild(element1);
How can I update the SOAP xml element value from an soap xml file using c#.net? My file is as below:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<Action xmlns="http://www.w3.org/2005/08/addressing">http://extn.ssac.ee.sim.dsh.cms.hhs.gov/SsaCompositePortType/VerifySSAResponse</Action>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:27f0af81-0da7-441f-83a7-fb2beaf30664</MessageID>
<RelatesTo xmlns="http://www.w3.org/2005/08/addressing">uuid:e8dcd685-cb86-400a-8059-dcad985a7ea7</RelatesTo>
</soap:Header>
<soap:Body>
<exch:SSACompositeResponse xmlns:exch="http://ssac.ee.sim.dsh.cms.hhs.gov">
<ssac:SSACompositeIndividualResponse xmlns:ssac="http://extn.ssac.ee.sim.dsh.cms.hhs.gov">
<ssac:ResponseMetadata>
<ssac:ResponseCode>HS000000</ssac:ResponseCode>
<ssac:ResponseDescriptionText>Success</ssac:ResponseDescriptionText>
</ssac:ResponseMetadata>
<ssac:PersonSSNIdentification>199123051</ssac:PersonSSNIdentification>
<ssac:SSAResponse>
<ssac:SSNVerificationIndicator>true</ssac:SSNVerificationIndicator>
<ssac:DeathConfirmationCode>Unconfirmed</ssac:DeathConfirmationCode>
<nc:PersonUSCitizenIndicator xmlns:nc="http://niem.gov/niem/niem-core/2.0">true</nc:PersonUSCitizenIndicator>
<ssac:PersonIncarcerationInformationIndicator>false</ssac:PersonIncarcerationInformationIndicator>
<ssac:SSATitleIIAnnualIncomeInformationIndicator>false</ssac:SSATitleIIAnnualIncomeInformationIndicator>
<ssac:SSATitleIIMonthlyIncomeInformationIndicator>false</ssac:SSATitleIIMonthlyIncomeInformationIndicator>
<ssac:SSAQuartersOfCoverageInformationIndicator>false</ssac:SSAQuartersOfCoverageInformationIndicator>
</ssac:SSAResponse>
</ssac:SSACompositeIndividualResponse>
</exch:SSACompositeResponse>
Here I want to update ssac:PersonSSNIdentification (199123051) value to 9876543210?
XmlNamespaceManager xnm;
xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
var xmlDoc = new XmlDocument();
xmlDoc.Load(newSSAPathName);
XmlNodeList aNodes = xmlDoc.SelectNodes("/Envelope/Body/SSACompositeResponse/SSACompositeIndividualResponse");
foreach (XmlNode aNode in aNodes)
{ var innerXmlNode = aNode.SelectSingleNode("/PersonSSNIdentification");
if (innerXmlNode != null)
{ innerXmlNode.Value = lstSsn[0];
}
}
xmlDoc.Save(newSSAPathName);
But this doesn't work...is there any way...
I'd recommend doing this with LINQ to XML rather than the older XmlDocument API.
First, load your XML into an XDocument:
var doc = XDocument.Load(newSSAPathName);
Then, define an XNamespace for each of the namespaces you have in your XML:
var soap = (XNamespace)"http://www.w3.org/2003/05/soap-envelope";
var exch = (XNamespace)"http://ssac.ee.sim.dsh.cms.hhs.gov";
var ssac = (XNamespace)"http://extn.ssac.ee.sim.dsh.cms.hhs.gov";
Now query for all elements at the required depth in the XML hierarchy with the required fully qualified names:
var ssnIds = doc.Elements(soap + "Envelope")
.Elements(soap + "Body")
.Elements(exch + "SSACompositeResponse")
.Elements(ssac + "SSACompositeIndividualResponse")
.Elements(ssac + "PersonSSNIdentification");
Finally, change the appropriate element value:
foreach (var ssnId in ssnIds)
if (ssnId.Value == "199123051")
ssnId.Value = "9876543210";
Alternatively, if you do want to use an XPATH query, you need to populate an XmlNamespaceManager with all 3 namespaces. The documentation for XPathSelectElements(XNode, String, IXmlNamespaceResolver) shows how to do this. Then use the prefixes you chose corresponding to each namespace in your XPATH query:
using (var reader = XmlReader.Create(newSSAPathName))
{
var doc = XDocument.Load(reader);
// Set up a namespaceManager as described in https://msdn.microsoft.com/en-us/library/bb351355%28v=vs.110%29.aspx
var nameTable = reader.NameTable;
var namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
namespaceManager.AddNamespace("exch", "http://ssac.ee.sim.dsh.cms.hhs.gov");
namespaceManager.AddNamespace("ssac", "http://extn.ssac.ee.sim.dsh.cms.hhs.gov");
var ssnIds = doc.XPathSelectElements("soap:Envelope/soap:Body/exch:SSACompositeResponse/ssac:SSACompositeIndividualResponse/ssac:PersonSSNIdentification", namespaceManager);
foreach (var ssnId in ssnIds)
if (ssnId.Value == "199123051")
ssnId.Value = "9876543210";
}
Be sure to do using System.Xml.XPath; at the beginning of the file since XPathSelectElements is an extension method.
Update
Using XmlDocument, the equivalent XPATH query is:
var xmlDoc = new XmlDocument();
xmlDoc.Load(newSSAPathName);
var nameTable = xmlDoc.NameTable;
var namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
namespaceManager.AddNamespace("exch", "http://ssac.ee.sim.dsh.cms.hhs.gov");
namespaceManager.AddNamespace("ssac", "http://extn.ssac.ee.sim.dsh.cms.hhs.gov");
var ssnIds = xmlDoc.SelectNodes("soap:Envelope/soap:Body/exch:SSACompositeResponse/ssac:SSACompositeIndividualResponse/ssac:PersonSSNIdentification", namespaceManager);
foreach (XmlNode ssnId in ssnIds)
if (ssnId.InnerText == "199123051")
ssnId.InnerText = "9876543210";
I have the following XML name Sample.xml which I am trying to query uniqueID with XDocument:
<Request>
<Person xmlns="http://CompanyName.AppName.version1" uniqueID="3221">
<AccountNo>83838</AccountNo>
<FirstName>Tom</FirstName>
<LastName>Jackson</LastName>
</Person>
<Person xmlns="http://CompanyName.AppName.version1" uniqueID="21132">
<AccountNo>789875</AccountNo>
<FirstName>Chris</FirstName>
<LastName>Smith</LastName>
</Person>
</Request>
How do i write code to extract uniqueID of all persons.
You can use LINQ to XML to retrieve the unique ID from your XML document.
string xml = "<Request><Person xmlns='http://CompanyName.AppName.version1' uniqueID='3221'><AccountNo>83838</AccountNo><FirstName>Tom</FirstName><LastName>Jackson</LastName></Person><Person xmlns='http://CompanyName.AppName.version1' uniqueID='21132'><AccountNo>789875</AccountNo><FirstName>Chris</FirstName><LastName>Smith</LastName></Person></Request>";
XDocument doc = XDocument.Parse(xml);
XNamespace ns = "http://CompanyName.AppName.version1";
var uniqueIDs = doc.Descendants(ns + "Person")
.Select(p => p.Attribute("uniqueID").Value)
.ToList();
Try below code With XmlDocument in place
string xml = "<Request><Person xmlns='http://CompanyName.AppName.version1' uniqueID='3221'><AccountNo>83838</AccountNo><FirstName>Tom</FirstName><LastName>Jackson</LastName></Person><Person xmlns='http://CompanyName.AppName.version1' uniqueID='21132'><AccountNo>789875</AccountNo><FirstName>Chris</FirstName><LastName>Smith</LastName></Person></Request>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Person");
foreach (XmlNode node in nodeList)
{
Console.WriteLine(node.Attributes["uniqueID"].Value);
}
You can get the Unique ID by:
string xml="Your XML String";
XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(xml));
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
if (chldNode.HasChildNodes)
{
foreach (XmlNode item in node.ChildNodes)
{
string uniqueID = chldNode.Attributes["uniqueID"].Value;
Response.Write(employeeName + "<br />");
}
}
}
am trying to generate an XML document like this through code.
<TestRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost:2292/RMSchema.xsd">
<Version>3</Version>
<ApplicationHeader>
<AppLanguage />
<UserId>rmservice</UserId>
</ApplicationHeader>
<CustomerData>
<ExistingCustomerData>
<MTN>2084127182</MTN>
</ExistingCustomerData>
</CustomerData>
</TestRequest>
I tried some samples. But they create xmlns for the children, which i dont need. Any help is really appreciated.
I have tried the below code. But it is adding only xmlns to all children, which i dont need
XmlDocument xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
XmlElement xRoot = xDocument.CreateElement("TestRequest", "XNamespace.Xmlns=http://www.w3.org/2001/XMLSchema-instance" + " xsi:noNamespaceSchemaLocation=" + "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = 1;
Thanks
Tutu
I have tried with
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
XmlElement xRoot = xDocument.CreateElement("xsi","RMRequest",xsi);
xRoot.SetAttribute("noNamespaceSchemaLocation", xsi, "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
Now the response is
<?xml version=\"1.0\" encoding=\"windows-1252\"?><xsi:TestRequest xsi:noNamespaceSchemaLocation=\"http://localhost:2292/RMSchema.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
Here is the awesome LINQ to XML. Enjoy!
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(new XDeclaration("1.0", "windows-1252", null),
new XElement("TestRequest",
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(xsi + "noNamespaceSchemaLocation", "http://localhost:2292/RMSchema.xsd"),
new XElement("Version",
new XText("3")
),
new XElement("ApplicationHeader",
new XElement("AppLanguage"),
new XElement("UserId",
new XText("rmservice")
)
),
new XElement("CustomerData",
new XElement("ExistingCustomerData",
new XElement("MTN",
new XText("2084127182")
)
)
)
)
);
doc.Save(filePath);
If you really want the old API, here it is:
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
var attr = xDocument.CreateAttribute("xsi", "noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
EDIT: From your comments, it looks like you want the xmlns:xsi and other attribute in that specific order. If so, you may have to trick the XmlDocument to add the xmlns:xsi attribute first.
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
// add namespace decl are attribute
var attr = xDocument.CreateAttribute("xmlns:xsi");
attr.Value = xsi;
xRoot.Attributes.Append(attr);
// no need to specify prefix, XmlDocument will figure it now
attr = xDocument.CreateAttribute("noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
Are you looking for something like this:-
XmlDocument xmldoc = new XmlDocument();
XmlNode root = xmldoc.AppendChild(xmldoc.CreateElement("Root"));
XmlNode child = root.AppendChild(xmldoc.CreateElement("Child"));
XmlAttribute childAtt =child.Attributes.Append(xmldoc.CreateAttribute("Attribute"));
childAtt.InnerText = "My innertext";
child.InnerText = "My node Innertext";
xmldoc.Save("ABC.xml");