public void DescribeReservedCacheNodesOfferingsMarshallTest() { var operation = service_model.FindOperation("DescribeReservedCacheNodesOfferings"); var request = InstantiateClassGenerator.Execute <DescribeReservedCacheNodesOfferingsRequest>(); var marshaller = new DescribeReservedCacheNodesOfferingsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeReservedCacheNodesOfferingsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeReservedCacheNodesOfferingsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); }
public void ListAllowedNodeTypeModificationsMarshallTest() { var operation = service_model.FindOperation("ListAllowedNodeTypeModifications"); var request = InstantiateClassGenerator.Execute <ListAllowedNodeTypeModificationsRequest>(); var marshaller = new ListAllowedNodeTypeModificationsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = ListAllowedNodeTypeModificationsResponseUnmarshaller.Instance.Unmarshall(context) as ListAllowedNodeTypeModificationsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); }
public void UpdateApplicationResourceLifecycleMarshallTest() { var operation = service_model.FindOperation("UpdateApplicationResourceLifecycle"); var request = InstantiateClassGenerator.Execute <UpdateApplicationResourceLifecycleRequest>(); var marshaller = new UpdateApplicationResourceLifecycleRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = UpdateApplicationResourceLifecycleResponseUnmarshaller.Instance.Unmarshall(context) as UpdateApplicationResourceLifecycleResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); }
public void AssumeRoleWithWebIdentityMarshallTest() { var operation = service_model.FindOperation("AssumeRoleWithWebIdentity"); var request = InstantiateClassGenerator.Execute <AssumeRoleWithWebIdentityRequest>(); var marshaller = new AssumeRoleWithWebIdentityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance.Unmarshall(context) as AssumeRoleWithWebIdentityResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); }
public void ChangeMessageVisibilityBatchMarshallTest() { var operation = service_model.FindOperation("ChangeMessageVisibilityBatch"); var request = InstantiateClassGenerator.Execute <ChangeMessageVisibilityBatchRequest>(); var marshaller = new ChangeMessageVisibilityBatchRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = ChangeMessageVisibilityBatchResponseUnmarshaller.Instance.Unmarshall(context) as ChangeMessageVisibilityBatchResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); }
public void TerminateInstanceInAutoScalingGroupMarshallTest() { var operation = service_model.FindOperation("TerminateInstanceInAutoScalingGroup"); var request = InstantiateClassGenerator.Execute <TerminateInstanceInAutoScalingGroupRequest>(); var marshaller = new TerminateInstanceInAutoScalingGroupRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = TerminateInstanceInAutoScalingGroupResponseUnmarshaller.Instance.Unmarshall(context) as TerminateInstanceInAutoScalingGroupResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); }
public void ModifyReplicationGroupShardConfigurationMarshallTest() { var operation = service_model.FindOperation("ModifyReplicationGroupShardConfiguration"); var request = InstantiateClassGenerator.Execute <ModifyReplicationGroupShardConfigurationRequest>(); var marshaller = new ModifyReplicationGroupShardConfigurationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = ModifyReplicationGroupShardConfigurationResponseUnmarshaller.Instance.Unmarshall(context) as ModifyReplicationGroupShardConfigurationResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); }
public void SetLoadBalancerPoliciesOfListenerMarshallTest() { var operation = service_model.FindOperation("SetLoadBalancerPoliciesOfListener"); var request = InstantiateClassGenerator.Execute <SetLoadBalancerPoliciesOfListenerRequest>(); var marshaller = new SetLoadBalancerPoliciesOfListenerRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = SetLoadBalancerPoliciesOfListenerResponseUnmarshaller.Instance.Unmarshall(context) as SetLoadBalancerPoliciesOfListenerResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); }
public static string Generate(string xml, string elem) { XmlDocument xmlDoc = new XmlDocument(); string ret = ""; using (StringWriter sWriter = new StringWriter()) { using (XmlWriter xWriter = XmlTextWriter.Create(sWriter, new XmlWriterSettings() { Indent = true })) { using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml))) { xmlDoc.Load(stream); XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable); ns.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); using (XmlNodeList childNodes = xmlDoc.SelectNodes("xsd:schema/xsd:element[@name!='" + elem + "']", ns)) { foreach (XmlNode childNode in childNodes) { childNode.ParentNode.RemoveChild(childNode); } } XmlSchema schema = XmlSchema.Read(new XmlNodeReader(xmlDoc), null); schema.Namespaces.Add("wd", "urn:com.workday/bsvc"); XmlSampleGenerator gen = new XmlSampleGenerator(schema, null); gen.ListLength = 1; gen.MaxThreshold = 1; gen.WriteXml(xWriter); } ret = sWriter.ToString(); ret = ret.Replace("p2=", "wd="); ret = ret.Replace("p2:", "wd:"); ret = ret.Replace("encoding=\"utf-16\"", "encoding=\"UTF-8\""); } } return ret; }
public static void Main(string[] args) { XmlSchemaSet schemas = new XmlSchemaSet(); XmlQualifiedName qname = XmlQualifiedName.Empty; string localName = string.Empty; string ns = string.Empty; int max = 0; int listLength = 0; for (int i = 0; i < args.Length; i++) { string arg = args[i]; string value = string.Empty; bool argument = false; if (arg.StartsWith("/") || arg.StartsWith("-")) { argument = true; int colonPos = arg.IndexOf(":"); if (colonPos != -1) { value = arg.Substring(colonPos + 1); arg = arg.Substring(0, colonPos); } } arg = arg.ToLower(CultureInfo.InvariantCulture); if (!argument && arg.EndsWith(".xsd")) { schemas.Add(null, args[i]); } else if (ArgumentMatch(arg, "?") || ArgumentMatch(arg, "help")) { WriteHelp(); return; } else if (ArgumentMatch(arg, "localname")) { localName = value; } else if (ArgumentMatch(arg, "namespace")) { ns = value; } else if (ArgumentMatch(arg, "maxthreshold")) { max = Int16.Parse(value); } else if (ArgumentMatch(arg, "listlength")) { listLength = Int16.Parse(value); } else { throw new ArgumentException(args[i]); } } if (args.Length == 0) { WriteHelp(); return; } XmlTextWriter textWriter = new XmlTextWriter("Sample.xml", null); textWriter.Formatting = Formatting.Indented; XmlSampleGenerator genr = new XmlSampleGenerator(schemas, qname); if (max > 0) { genr.MaxThreshold = max; } if (listLength > 0) { genr.ListLength = listLength; } genr.WriteXml(textWriter); }
private void DeserializeSampleXml(string pattern, Assembly assembly) { var files = Glob.Glob.ExpandNames(pattern); var set = new XmlSchemaSet(); var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f), (s, e) => { Assert.True(false, e.Message); })); foreach (var s in schemas) { set.Add(s); } set.Compile(); foreach (var rootElement in set.GlobalElements.Values.Cast <XmlSchemaElement>().Where(e => !e.IsAbstract)) { var type = FindType(assembly, rootElement.QualifiedName); var serializer = new XmlSerializer(type); var generator = new XmlSampleGenerator(set, rootElement.QualifiedName); var sb = new StringBuilder(); using (var xw = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true })) { // generate sample xml generator.WriteXml(xw); var xml = sb.ToString(); File.WriteAllText("xml.xml", xml); // deserialize from sample var sr = new StringReader(xml); var o = serializer.Deserialize(sr); // serialize back to xml var xml2 = Serialize(serializer, o); File.WriteAllText("xml2.xml", xml2); // validate serialized xml XmlReaderSettings settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = set }; settings.ValidationEventHandler += (s, e) => { // generator doesn't generate valid values where pattern restrictions exist, e.g. email if (!e.Message.Contains("The Pattern constraint failed")) { Assert.True(false, e.Message); } }; XmlReader reader = XmlReader.Create(new StringReader(xml2), settings); while (reader.Read()) { ; } // deserialize again sr = new StringReader(xml2); var o2 = serializer.Deserialize(sr); AssertEx.Equal(o, o2); } } }
private void btnGenerate_Click(object sender, RoutedEventArgs e) { XmlSchemaSet schemas = new XmlSchemaSet(); XmlQualifiedName qname; object selItem = cboRoot.SelectedItem; if (selItem == null) { qname = XmlQualifiedName.Empty; } else { qname = new XmlQualifiedName(selItem.ToString()); } int max = 0; int listLength = 0; try { schemas.Add(null, _currentFileName); } catch (Exception ex) { MessageBox.Show(Application.Current.MainWindow, "Error in XSD file: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (!string.IsNullOrEmpty(edtMaxThreshold.Text)) { max = Int16.Parse(edtMaxThreshold.Text); } if (!string.IsNullOrEmpty(edtListLength.Text)) { listLength = Int16.Parse(edtListLength.Text); } try { using (StringWriter writer = new StringWriter()) using (XmlTextWriter textWriter = new XmlTextWriter(writer)) { textWriter.Formatting = Formatting.Indented; XmlSampleGenerator genr = new XmlSampleGenerator(schemas, qname); if (max > 0) { genr.MaxThreshold = max; } if (listLength > 0) { genr.ListLength = listLength; } genr.WriteXml(textWriter); edtResult.Text = writer.ToString(); } _foldingStrategy.UpdateFoldings(_foldingManager, edtResult.Document); } catch (Exception ex) { MessageBox.Show(Application.Current.MainWindow, "Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public Mensagem LerXsd(string xsdPath, string nomeMensagem) { Mensagem mensagem = new Mensagem(); mensagem.nome = nomeMensagem; using (var stream = new MemoryStream(File.ReadAllBytes(xsdPath))) { var schema = XmlSchema.Read(XmlReader.Create(stream), null); var gen = new XmlSampleGenerator(schema, new XmlQualifiedName("rootElement")); try { var xmlString = new StringWriter(); gen.WriteXml(XmlWriter.Create(xmlString)); //var texto = xmlString.ToString(); if (!xmlString.ToString().Equals("")) { XmlDocument document = new XmlDocument(); document.LoadXml(xmlString.ToString()); mensagem.xml = xmlString.ToString(); XmlElement root = document.DocumentElement; StringBuilder sb = new StringBuilder("<form> <br>"); foreach (XmlNode noPrincipal in root.ChildNodes) { sb.Append("<fieldset> <legend>" + noPrincipal.Name + "</legend> </br>"); bool noTemFilhos = noPrincipal.HasChildNodes; //Console.WriteLine(noPrincipal.Name); foreach (XmlNode subNo in noPrincipal.ChildNodes) { //input //ou um field novo // Console.WriteLine(subNo.Name); if (subNo.ChildNodes.Count > 1) { bool subNoFilho = subNo.HasChildNodes; sb.Append("<fieldset> <legend>" + subNo.Name + "</legend> </br>"); foreach (XmlNode subNo2 in subNo.ChildNodes) { sb.Append("<label>" + subNo2.Name + "<label/>"); sb.Append("<input type='text' value=" + subNo2.Name + "'/></br>"); //Console.WriteLine(subNo2.Name); bool subNoFilho2 = subNo2.HasChildNodes; } sb.Append("</fieldset>"); } else { if (subNo.Name.Contains("text")) { sb.Append("<label>" + subNo.InnerText + "<label/>"); sb.Append("<input type='text' value=" + subNo.InnerText + "'/></br>"); } else { sb.Append("<label>" + subNo.Name + "<label/>"); sb.Append("<input type='text' value=" + subNo.Name + "'/></br>"); } } } sb.Append("</fieldset>"); //fechar o field set } sb.Append("</form>"); mensagem.html = sb.ToString(); return(mensagem); } } catch (Exception ex) { Console.WriteLine("Erro ao ler:" + xsdPath); } } return(null); }
private void DeserializeSampleXml(string pattern, Assembly assembly) { var files = Glob.ExpandNames(pattern); var set = new XmlSchemaSet(); var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f), (s, e) => { Assert.True(false, e.Message); })); foreach (var s in schemas) { set.Add(s); } set.Compile(); var anyValidXml = false; foreach (var rootElement in set.GlobalElements.Values.Cast <XmlSchemaElement>().Where(e => !e.IsAbstract && !(e.ElementSchemaType is XmlSchemaSimpleType))) { var type = FindType(assembly, rootElement.QualifiedName); var serializer = new XmlSerializer(type); var generator = new XmlSampleGenerator(set, rootElement.QualifiedName); var sb = new StringBuilder(); using (var xw = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true })) { // generate sample xml generator.WriteXml(xw); var xml = sb.ToString(); File.WriteAllText("xml.xml", xml); // validate serialized xml var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = set }; var invalid = false; void validate(object s, ValidationEventArgs e) { if (HandleValidationError(xml, e)) { invalid = true; } } settings.ValidationEventHandler += validate; var reader = XmlReader.Create(new StringReader(xml), settings); while (reader.Read()) { ; } settings.ValidationEventHandler -= validate; // generated xml is not schema valid -> skip if (invalid) { continue; } anyValidXml = true; // deserialize from sample var sr = new StringReader(xml); var o = serializer.Deserialize(sr); // serialize back to xml var xml2 = Serialize(serializer, o); File.WriteAllText("xml2.xml", xml2); void validate2(object s, ValidationEventArgs e) { if (HandleValidationError(xml2, e)) { throw e.Exception; } }; settings.ValidationEventHandler += validate2; reader = XmlReader.Create(new StringReader(xml2), settings); while (reader.Read()) { ; } settings.ValidationEventHandler -= validate2; // deserialize again sr = new StringReader(xml2); var o2 = serializer.Deserialize(sr); AssertEx.Equal(o, o2); } } Assert.True(anyValidXml, "No valid generated XML for this test"); }
static void Main(string[] args) { if (CreateOutputFolders() == false) { Console.ReadKey(); Environment.Exit(99); } const string xsltFilePath = "xs3p.xsl"; // Load XSLT XsltSettings settings = new XsltSettings(true, true); XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(xsltFilePath, settings, new XmlUrlResolver()); string schemaProjectDirectory = System.Environment.CurrentDirectory + "\\XSD"; // Look in the project output directory for all xsd files string[] files = Directory.GetFiles(schemaProjectDirectory, "*.xsd"); // Create the output directories for the generated HTML files, and code example files //string outputDirectory = Path.Combine(Environment.CurrentDirectory, "Generated HTML Docs"); //if (!Directory.Exists(outputDirectory)) // Directory.CreateDirectory(outputDirectory); //string exampleDirectory = Path.Combine(Environment.CurrentDirectory, "Generated Examples"); //if (!Directory.Exists(exampleDirectory)) // Directory.CreateDirectory(exampleDirectory); // For each XSD file, create the HTML documentation, and examples (.cs, .vb, .xml, json) Console.WriteLine("Generating Files....."); foreach (string xsdFilePath in files) { //Don't create HTML documentation or XML samples for base schema if (xsdFilePath == schemaProjectDirectory + "\\Common.xsd" || xsdFilePath == schemaProjectDirectory + "\\ISOCountryCodeType-V2006.xsd" || xsdFilePath == schemaProjectDirectory + "\\ISOCurrencyCodeType.xsd" || xsdFilePath == schemaProjectDirectory + "\\MessageContext.xsd" || xsdFilePath == schemaProjectDirectory + "\\Meta.xsd") { continue; } #region Generate the HTML documentation string outHtmlFileName = Path.Combine(sGeneratedPath + "\\HTML\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".html"; using (StreamWriter outHtmlfile = new StreamWriter(outHtmlFileName)) { string documentTitle = Path.GetFileNameWithoutExtension(xsdFilePath); documentTitle = documentTitle.Replace("CUFX_", ""); documentTitle = documentTitle.Replace("_", " "); XsltArgumentList argsList = new XsltArgumentList(); argsList.AddParam("title", "", documentTitle); argsList.AddParam("currentDateTime", "", DateTime.Now.ToString("d")); using (XmlTextReader xsdReader = new XmlTextReader(xsdFilePath)) { XPathNavigator nav = new XPathDocument(xsdReader).CreateNavigator(); try { transformer.Transform(nav, argsList, outHtmlfile); } catch (XsltException xsltEx) { Console.WriteLine("Could not transform the XSD file [{0}]. Message: [{1}] line: [{2}], position: [{3}]", xsdFilePath, xsltEx.Message, xsltEx.LineNumber, xsltEx.LinePosition); Console.ReadKey(); } xsdReader.Close(); } outHtmlfile.Close(); //Console.WriteLine("HTML Files Created"); } #endregion #region Generate the XML/JSON examples string outXmlFileName = Path.Combine(sGeneratedPath + "\\XML\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".xml"; using (XmlTextWriter outXmlFile = new XmlTextWriter(outXmlFileName, null)) { outXmlFile.Formatting = System.Xml.Formatting.Indented; XmlQualifiedName qname = new XmlQualifiedName("AccountList", "http://cufxstandards.com/v2/Account.xsd"); XmlSampleGenerator generator = new XmlSampleGenerator(xsdFilePath, qname); generator.WriteXml(outXmlFile); //Console.WriteLine("XML Files Created"); } string outJSONFileName = Path.Combine(sGeneratedPath + "\\JSON\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".json"; JsonGenerator.GenerateJsonFromXml(outXmlFileName, outJSONFileName); #endregion // Generate one .cs for all the types and place it in the Schemas project //string cufxCsFile = Path.Combine(schemaProjectDirectory, "CUFX.cs"); //string cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".cs"; //string cufxVbFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".vb"; //CodeGenerator.GenerateCodeFromXsd(xsdFilePath, cufxCsFile, cufxVbFile); //CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile); //JsonGenerator.GenerateJsonFromCs(cufxCsFile, Path.Combine(sGeneratedPath + "\\JSON\\", Path.GetFileNameWithoutExtension(cufxCsFile)) + ".json"); //#region Generate the WCF examples //cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".cs"; //string cufxVbFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".vb"; //CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile); //CodeGenerator.GenerateCodeFromXsd(xsdFilePath, cufxCsFile, cufxVbFile); //Now Generate the WCF Files //Converter converter = new Converter(xsdFilePath); //bool wasSuccessful = converter.Convert(cufxCsFile); //#endregion } Console.WriteLine("HTML & XML Files Created....."); #region Generate the WCF examples // Generate one .cs for all the types and place it in the Schemas project string cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", "CUFX.cs"); //CodeGeneratorV1.GenerateCodeFromXsds(files, sGeneratedPath + "\\WCF\\CUFX.vb", sGeneratedPath + "\\WCF\\CUFX.cs"); //Working Single WCF Generator CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile); //Now Generate the WCF File //Converter converter = new Converter(sGeneratedPath + "\\WCF\\CUFXTemp.cs"); //bool wasSuccessful = converter.Convert(sGeneratedPath + "\\WCF\\CUFX.cs"); //System.IO.File.Delete(sGeneratedPath + "\\WCF\\CUFXTemp.cs"); //if (wasSuccessful) //{ Console.WriteLine("WCF File Created"); //} #endregion Console.WriteLine("JSON File Created"); Console.WriteLine("Press any key to close"); Console.ReadLine(); }
public string BuildRequest(string operation) { // load operation's input message // MESSAGE = portType/operation[].(name=OPERATION)/input.message var operations = wsdl_object.XPathElements($"/wsdl:portType[1]/wsdl:operation[@name='{operation}']/wsdl:input[1]", xml_ns_mgr); var input_message = operations.FirstOrDefault().Attribute("message").LocalValue(namespaces.Keys).value; // load message's main element // ELEMENT = message[].(name=MESSAGE)/(part.(name="body")).element var messages = wsdl_object.XPathElements($"/wsdl:message[@name='{input_message}']/wsdl:part[@element]", xml_ns_mgr); var(xsd_element, ns_prefix) = messages.FirstOrDefault().Attribute("element").LocalValue(namespaces.Keys); using var stream_xmldom = new MemoryStream(); using var stream_schema = new MemoryStream(); using var stream_sample = new MemoryStream(); using var stream_xmlout = new MemoryStream(); using var stream_reader = new StreamReader(stream_xmlout, true); using var xml_writer = XmlWriter.Create(stream_sample); // extract XSD from WSDL var xelement_schema = wsdl_object.XPathElements("/wsdl:types/xsd:schema[1]", xml_ns_mgr).FirstOrDefault(); // remove all <element ref="schema"> (causes problems in sample generation) var nodes = xelement_schema.XPathElements("//xsd:element[@ref]", xml_ns_mgr).ToList(); foreach (var element in from XElement element in nodes where (element.Parent != null) && (element.Attribute("ref").LocalValue(namespaces.Keys).value == "schema") select element) { element.Remove(); } // add targetNamespace xelement_schema.Save(stream_xmldom, SaveOptions.DisableFormatting); var xml_dom_schema = new XmlDocument(); stream_xmldom.Position = 0; xml_dom_schema.Load(stream_xmldom); xml_dom_schema.DocumentElement.SetAttribute($"xmlns:{ns_prefix}", targetNamespace); xml_dom_schema.Save(stream_schema); // generate sample XML from XSD stream_schema.Position = 0; var xml_schema = XmlSchema.Read(stream_schema, (s, v) => { throw new XmlSchemaException(v.Message); }); var generator = new XmlSampleGenerator(xml_schema, new XmlQualifiedName(xsd_element, targetNamespace)); generator.WriteXml(xml_writer); xml_writer.Flush(); // load XML var xml_dom_inner = new XmlDocument(); stream_sample.Position = 0; xml_dom_inner.Load(stream_sample); // create SOAP envelope var xml_dom_outer = new XmlDocument() { PreserveWhitespace = false }; var elm_envelope = xml_dom_outer.CreateElement("soap", "Envelope", NS_ENV); var elm_body = xml_dom_outer.CreateElement("soap", "Body", NS_ENV); var elm_operation = xml_dom_outer.CreateElement(operation, targetNamespace); foreach (var node in from XmlNode? node in xml_dom_inner.DocumentElement.ChildNodes where node !.NodeType == XmlNodeType.Element select node) { elm_operation.AppendChild(xml_dom_outer.ImportNode(node, true)); } elm_body.AppendChild(elm_operation); elm_envelope.AppendChild(elm_body); xml_dom_outer.AppendChild(elm_envelope); xml_dom_outer.DocumentElement.SetAttribute("xmlns:xsi", NS_XSI); xml_dom_outer.DocumentElement.SetAttribute("xmlns:xsd", NS_XSD); xml_dom_outer.Save(stream_xmlout); // output SOAP stream_xmlout.Position = 0; var xml_string = stream_reader.ReadToEnd(); return(xml_string); }