I want to see below format as output of my webservice but it is return empty, would you mind help me to how figure it out?
I am using asp.net2
I would like to receive out put like below:
<LIST OF CUSTOMER>
<CustomerData>
<V_CUST_CODE value="c1"/>
<V_CUST_NAME value="Customer 1"/>
</CustomerData>
<CustomerData>
<V_CUST_CODE value="c2"/>
<V_CUST_NAME value="Customer 2"/>
</CustomerData>
<CustomerData>
<V_CUST_CODE value="c2"/>
<V_CUST_NAME value="Customer 2"/>
</CustomerData>
<LIST OF CUSTOMER/>
my current out put:
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfCustomerData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://123.23.45.34/sms/" />
my webservice
[WebMethod]
public List<CustomerData> getFMSCustomerName()
{
string[] cols = {"V_CUST_CODE", "V_CUST_NAME"};
ArrayList CustomerList = (ArrayList)db.Select(cols, "table1", "", "order by V_CUST_NAME");
List<CustomerData> cd = new List<CustomerData>();
foreach(DataRow dr in CustomerList)
cd.Add(new CustomerData(dr["V_CUST_CODE"].ToString(), dr["V_CUST_NAME"].ToString()));
return cd;
}
public class CustomerData
{
private string _V_CUST_CODE;
private string _V_CUST_NAME;
public String V_CUST_CODE
{
get
{
return this._V_CUST_CODE;
}
set
{
this._V_CUST_CODE = value;
}
}
public String V_CUST_NAME
{
get
{
return this._V_CUST_NAME;
}
set
{
this._V_CUST_NAME = value;
}
}
public CustomerData(String V_CUST_CODE, String V_CUST_NAME)
{
this.V_CUST_CODE = V_CUST_CODE;
this.V_CUST_NAME = V_CUST_NAME;
}
public CustomerData() { }
}
I solve my problem by using below code:
public String getFMSCustomerName()
{
string[] cols = {"V_CUST_CODE", "V_CUST_NAME"};
ArrayList CustomerList = (ArrayList)db.Select(cols, "table1", " V_STATUS = 'A'", "order by V_CUST_NAME");
//List<CustomerData> cd = new List<CustomerData>();
XmlDocument doc = new XmlDocument();
XmlNode CustomersNode = doc.CreateElement("Customers");
doc.AppendChild(CustomersNode);
foreach (DataRow dr in CustomerList)
{
// cd.Add(new CustomerData(dr["V_CUST_CODE"].ToString(), dr["V_CUST_NAME"].ToString()));
XmlNode customerNode = doc.CreateElement("Customer");
XmlNode V_CUST_CODENode = doc.CreateElement("V_CUST_CODE");
V_CUST_CODENode.AppendChild(doc.CreateTextNode(dr["V_CUST_CODE"].ToString()));
customerNode.AppendChild(V_CUST_CODENode);
XmlNode V_CUST_NAMENode = doc.CreateElement("V_CUST_NAME");
V_CUST_NAMENode.AppendChild(doc.CreateTextNode(dr["V_CUST_NAME"].ToString()));
customerNode.AppendChild(V_CUST_NAMENode);
CustomersNode.AppendChild(customerNode);
}
return doc.OuterXml;
}
Related
I have the following xml:
<?xml version="1.0" encoding="UTF-8"?>
<TestRun id="2fc10ef6-b97f-49e5-a58d-863dfb599cb3" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Times creation="2019-08-26T11:27:34.3642040+00:00" queuing="2019-08-26T11:27:34.3642190+00:00" start="2019-08-26T11:27:29.1640690+00:00" finish="2019-08-26T11:29:28.0320260+00:00" />
<TestSettings name="default" id="3c3c8ad0-9076-4c83-a283-03f5490f906b">
<Deployment runDeploymentRoot="_9e3d0007c2b9 2019-08-26 11:27:34" />
</TestSettings>
<Results>
<UnitTestResult testName="FirstName" outcome="Passed" testListId="1">
<Output>
</Output>
</UnitTestResult>
<UnitTestResult testName="SecondName" outcome="Passed" testListId="2">
<Output>
</Output>
</UnitTestResult>
<UnitTestResult testName="Thirdname" outcome="Passed" testListId="3">
<Output>
</Output>
</UnitTestResult>
</Results>
</TestRun>
And i have the following classes:
{
public string testName { get; set; }
public string outcome { get; set; }
}
public DtoHeader ReadXmlFile()
{
var binDirectory = Path.GetDirectoryName(GetType().GetTypeInfo().Assembly.Location);
var file = Path.Combine(binDirectory, "myfile.xml");
var xDocument = XDocument.Load(file);
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(new NameTable());
nameSpaceManager.AddNamespace("ns", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010");
var items = xDocument.Root.XPathSelectElements("./ns:Results", nameSpaceManager).ToArray();
if (!items.Any())
{
}
return new DtoHeader
{
testName = items.Descendants().Attributes("testName").First().Value,
};
}
I will like to extract the value of the attributes testName and outcome and put these values in a list.However, I have not been able to do this after going through multiple examples.
items.Descendants().Attributes("testName") returns IEnumerable of XAttribute.
You need to select the Value member of each XAttibute and return a list.
var list = items.Descendants().Attributes("testName").Select(t => t.Value).ToList();
Edit:
Return as DtoHeader List:
var list = items.Descendants().Attributes("testName").Select(t =>
new DtoHeader
{
testName = t.Value
}
).ToList();
To get a list of DtoHeaders using Linq2Xml you could use the following approach:
var headers = xDocument.Root.XPathSelectElements("./ns:Results", nameSpaceManager)
.Elements()
.Select(x => new DtoHeader
{
testName = x.Attribute("testName").Value,
outcome = x.Attribute("outcome").Value
})
.ToList();
I suggest to use xmltocsharp to convert the xml to classes and use XmlSerializerto do the rest of the job. Here is the simplified code to get the desired result.
string requestBody = ReadFile("XMLFile1.xml");
XmlSerializer serializer = new XmlSerializer(typeof(TestRun));
using (TextReader reader = new StringReader(requestBody))
{
//convert the xml to object
TestRun testRun = (TestRun)serializer.Deserialize(reader);
foreach (var result in testRun.Results.UnitTestResult)
{
Console.WriteLine($"{result.TestName} : {result.Outcome}");
}
}
var doc = XDocument.Load(file);
var list = new System.Collections.Generic.List<DtoHeader>();
foreach (var n in doc.Descendants().First(node => node.Name.LocalName == "Results").Elements().Where(e => e.Name.LocalName == "UnitTestResult"))
{
list.Add(new DtoHeader
{
outcome = n.Attribute("outcome").Value,
testName = n.Attribute("testName").Value,
});
}
I have a custom service class named as HotelClient (this class consumes Travelport's Universal API) with below code in one of the it's method:
try
{
var httpHeaders = Helper.ReturnHttpHeader();
hotelSearchclient.Endpoint.EndpointBehaviors.Add(new HttpHeadersEndpointBehavior(httpHeaders));
hotelSearchAvailabilityResponse = hotelSearchclient.service(hotelSearchAvailabilityRequest);
}
catch (Exception se)
{
hotelSearchclient.Abort();
}
return hotelSearchAvailabilityResponse;
When I run the code I get caught in catch block with below message:
{"The provided URI scheme 'https' is invalid; expected 'http'.\r\nParameter name: via"}
and the api end point is "https://apac.universal-api.pp.travelport.com/B2BGateway/connect/uAPI/HotelService".
What is the reason behind this type of error and what can be general solution. Thank you all.
In web.config/app.config, change
<binding name="someService" /> to
<binding name="someService" maxBufferPoolSize="524288"
maxBufferSize="2147483646" maxReceivedMessageSize="2147483646"
transferMode="Buffered">
<security mode="Transport">
<transport clientCredentialType="Basic" proxyCredentialType="None"
realm="AXIS" />
<message clientCredentialType="Certificate" algorithmSuite="Default" />
</security>
</binding>
If above solution doesn't work, then check for your credential expiration.
Solution provided above violets DRY principle, so link 'https://pastebin.com/QFhTTCqF' has complete web.config content.
Read Write textFile
--------------------
public void Loaddetails()
{
List<string> inputList = new List<string>();
string path = #"H:\Desktop\Prj Local\TradeList.txt";
StreamReader strReader = new StreamReader(path);
string line = "";
while ((line = strReader.ReadLine())!= null)
{
if(line.Length>0)
{
inputList.Add(line);
}
}
List<TradeList> ValidList = new List<TradeList>();
List<TradeList> InvalidList = new List<TradeList>();
foreach (string lsttovalid in inputList)
{
DateTime outDate = new DateTime();
DateTime outMatDate = new DateTime();
string[] splist = lsttovalid.Split(',');
if (splist[0]!=null && splist[0].StartsWith("TR")&&System.Text.RegularExpressions.Regex.IsMatch(splist[1],#"^ISIN\d{3}$") &&
DateTime.TryParseExact(splist[2],"MM/dd/yyyy", null, System.Globalization.DateTimeStyles.None, out outDate)&&
DateTime.TryParseExact(splist[3],"MM/dd/yyyy",null,System.Globalization.DateTimeStyles.None, out outMatDate)&&
outMatDate > outDate.AddYears(5)&& splist[4]!=null&& System.Text.RegularExpressions.Regex.IsMatch(splist[5],#"^[a-zA-Z]{3}$"))
{
TradeList vtd = new TradeList();
vtd.TradeId = splist[0];
vtd.TradeType = splist[1];
vtd.TradeDate = Convert.ToDateTime(splist[2]);
vtd.MaturityDate = Convert.ToDateTime(splist[3]);
vtd.Tradevalue = splist[4];
vtd.Currency = splist[5];
vtd.Money = Convert.ToInt32(splist[6]);
ValidList.Add(vtd);
}
else
{
TradeList etd = new TradeList();
etd.TradeId = splist[0];
etd.TradeType = splist[1];
etd.TradeDate = Convert.ToDateTime(splist[2]);
etd.MaturityDate = Convert.ToDateTime(splist[3]);
etd.Tradevalue = splist[4];
etd.Currency = splist[5];
etd.Money = Convert.ToInt32(splist[6]);
InvalidList.Add(etd);
}
}
List<string> Invalid = new List<string>();
foreach (TradeList trd in InvalidList)
{
StringBuilder sb = new StringBuilder();
sb.Append(trd.TradeId + ',');
sb.Append(trd.TradeType + ',');
sb.Append(Convert.ToDateTime(trd.TradeDate).ToShortDateString().ToString() + ',');
sb.Append(Convert.ToDateTime(trd.MaturityDate).ToShortDateString().ToString() + ',');
sb.Append(trd.Tradevalue + ',');
sb.Append(trd.Currency + ',');
sb.Append(trd.Money);
string str = sb.ToString();
Invalid.Add(str);
}
string Epath = #"H:\Desktop\Prj Local\ErrorList.txt";
if (File.Exists(Epath))
{
File.Delete(Epath);
}
using (StreamWriter swrite = new StreamWriter(Epath))
{
foreach (var lines in Invalid)
{
swrite.WriteLine(lines);
}
}
}
static void Main(string[] args)
{
Program P = new Program();
P.Loaddetails();
//Console.WriteLine(Result("CVB000","10/07/2017"));
Console.ReadLine();
}
XML
------
namespace ConsoleApplication12
{
[Serializable]
public class Trade
{
public int tradeid;
public string tradename;
public string tradeemail;
public DateTime tradedate;
}
}
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
List<Trade> lstTd = new List<Trade>();
XElement xe = XElement.Load(#"H:\Workspace\TEST\test.xml");
IEnumerable<XElement> iExe= xe.Elements();
foreach(var ele in iExe)
{
Trade trd = new Trade();
trd.tradeid = Convert.ToInt32(ele.Element("Id").Value);
trd.tradename = ele.Element("Name").Value;
trd.tradeemail = ele.Element("Email").Value;
trd.tradedate = Convert.ToDateTime(ele.Element("Date").Value);
lstTd.Add(trd);
}
XmlDocument xDoc = new XmlDocument();
XmlNode parentNode = xDoc.CreateElement("TradesMain");
xDoc.AppendChild(parentNode);
foreach (var trd in lstTd)
{
XmlNode secondParentNode = xDoc.CreateElement("Trades");
XmlNode firstChildNode = xDoc.CreateElement("TradeID");
firstChildNode.InnerText = trd.tradeid.ToString();
secondParentNode.AppendChild(firstChildNode);
XmlNode scChildNode = xDoc.CreateElement("TradeName");
scChildNode.InnerText = trd.tradename;
secondParentNode.AppendChild(scChildNode);
XmlNode trChildNode = xDoc.CreateElement("TradeEmail");
trChildNode.InnerText = trd.tradeemail;
secondParentNode.AppendChild(trChildNode);
XmlNode frChildNode = xDoc.CreateElement("TradeDate");
frChildNode.InnerText = trd.tradedate.ToString();
secondParentNode.AppendChild(frChildNode);
parentNode.AppendChild(secondParentNode);
}
xDoc.Save(#"H:\Workspace\TEST\testout.xml");
Console.WriteLine("ok");
XmlSerializer ser = new XmlSerializer(typeof(List<Trade>));
using (StreamWriter sw = new StreamWriter(#"H:\Workspace\TEST\testserout.xml"))
{
ser.Serialize(sw, lstTd);
}
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
- <Employees>
- <Employee>
<Id>1</Id>
<Name>Sam</Name>
<Email>Sam#gmail.com</Email>
<Date>12/24/2013</Date>
</Employee>
- <Employee>
<Id>2</Id>
<Name>Lucy</Name>
<Email>Lucy#gmail.com</Email>
<Date>12/26/2013</Date>
</Employee>
- <Employee>
<Id>3</Id>
<Name>Kate</Name>
<Email>Kate#gmail.com</Email>
<Date>12/27/2013</Date>
</Employee>
- <Employee>
<Id>1</Id>
<Name>Sam</Name>
<Email>Sam#gmail.com</Email>
<Date>12/24/2014</Date>
</Employee>
</Employees>
I'm looking for a easy way to convert my xml to json with the additional option to add the full xpath as attribute. Now I do it this way:
private static string XmlToJson(string xmlString)
{
return new JavaScriptSerializer().Serialize(GetXmlValues(XElement.Parse(xmlString)));
}
private static Dictionary<string, object> GetXmlValues(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements)
{
attr.Add("_children", xml.Elements().Select(e => GetXmlValues(e)));
attr.Add("_path", xml.GetPath());
}
else if (!xml.IsEmpty)
{
attr.Add("_value", xml.Value);
attr.Add("_path", xml.GetPath());
}
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
private static string GetPath(this XElement node)
{
string path = node.Name.LocalName;
XElement currentNode = node;
while (currentNode.Parent != null)
{
currentNode = currentNode.Parent;
path = currentNode.Name.LocalName + "/" + path;
}
return path;
}
But it looks circuitous compare to:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
But there for I have no idea how to add the path during the convertion?
But it looks circuitous compare to
Json.net uses it's own implementation of JsonConverter named XmlNodeConverter. So if you want it to look not circuitous, you can implement your own JsonConverter and use it:
var doc = XDocument.Parse(xml);
var json = JsonConvert.SerializeObject(doc, new MyXmlWithXPathJsonConverter());
This is a nice but quite complex task.
But a bit simpler way is to append your xml nodes with xpath attribute right before serialization. For example:
public void AppendXPath(XContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
var doc = container as XDocument;
if (doc != null)
AppendXPath(doc.Root, "", 1);
else
AppendXPath(container as XElement, "/", 1);
}
private void AppendXPath(XElement node, string parent, int num)
{
var path = $"{parent}/{node.Name}[{num}]";
if (node.Attribute("xpath") != null)
throw new InvalidOperationException($"Node {path} already contains xpath attribute");
var indicies = new Dictionary<XName, int>();
foreach (var child in node.Elements())
{
int index;
if (indicies.TryGetValue(child.Name, out index))
indicies[child.Name] = ++index;
else
indicies[child.Name] = index = 1;
AppendXPath(child, path, index);
}
node.Add(new XAttribute("xpath", path));
}
Test:
void Test()
{
var xml =
#"<xml>
<foo>
<one />
<other />
</foo>
<bar data=""abc"">
<item order=""3"" />
<item order=""1"">
<child whatever="""" />
</item>
</bar>
</xml>";
var doc = XDocument.Parse(xml);
AppendXPath(doc);
var json = JsonConvert.SerializeObject(doc, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
Result:
{
"xml": {
"#xpath": "/xml[1]",
"foo": {
"#xpath": "/xml[1]/foo[1]",
"one": {
"#xpath": "/xml[1]/foo[1]/one[1]"
},
"other": {
"#xpath": "/xml[1]/foo[1]/other[1]"
}
},
"bar": {
"#data": "abc",
"#xpath": "/xml[1]/bar[1]",
"item": [
{
"#order": "3",
"#xpath": "/xml[1]/bar[1]/item[1]"
},
{
"#order": "1",
"#xpath": "/xml[1]/bar[1]/item[2]",
"child": {
"#whatever": "",
"#xpath": "/xml[1]/bar[1]/item[2]/child[1]"
}
}
]
}
}
}
I have parsed the xml document and used a for loop to loop for getting different values in string, but when I try to return the value I get only the last value obtained, I want to return all the individual values so that I can store that values in any file format,
Below is my code,
XmlDocument xmlDOC = new XmlDocument();
xmlDOC.LoadXml(periodID_Value_Before_OffSet); // string storing my XML
var value = xmlDOC.GetElementsByTagName("value");
var xmlActions = new string[value.Count];
string values = "";
string Period1 = "";
string periodlevel_period1 = "";
var listOfStrings = new List<string>();
string modified_listofstrings = listOfStrings.ToString();
string arrayOfStrings = "";
for (int i = 0; i < value.Count; i++)
{
var xmlAttributeCollection = value[i].Attributes;
if (xmlAttributeCollection != null)
{
var action = xmlAttributeCollection["periodid"];
xmlActions[i] = action.Value;
values += action.Value + ",";
string vals = values.Split(',')[1];
string counts = values;
string[] periods = counts.Split(',');
Period1 = periods[i];
// periodlevel_period1 = Client.GetAttributeAsString(sessionId, Period1, "name", "");
modified_listofstrings = Client.GetAttributeAsString(sessionId, Period1, "name", "");
modified_listofstrings.ToArray().ToString();
//listOfStrings = periodlevel_period1;
}
}
return modified_listofstrings;
This modified_listofstrings string only return last on value, I want to return the array of the values all obtained while looping.
----------Updated question----------
below is my Sample XMl
<string xmlns="http://tempuri.org/">
<ResultSetHierarchy totalResultsReturned="1" totalResults="1" firstIndex="0" maxCount="-1">
<object id="SC.1938773693.238">
<measure.values>
<series id="SC.1938773693.108280985">
<value periodid="SC.1938773693.394400760" value="17" />
<value periodid="SC.1938773693.1282504058" value="15" />
<value periodid="SC.1938773693.1631528570" value="13" />
</series>
</object>
</ResultSetHierarchy>
</string>
I want output as "SC.1938773693.394400760":"17" and so on for all periodid
Based on the provided information I have updated the answer.
List<string> items = new List<string>();
XmlDocument xmlDOC = new XmlDocument();
xmlDOC.Load(#"E:\Delete Me\ConsoleApplication1\ConsoleApplication1\bin\Debug\List.xml");
var elements = xmlDOC.GetElementsByTagName("value");
foreach (var item in elements)
{
XmlElement value = (XmlElement)item;
items.Add(string.Format("{0}:{1}", value.GetAttribute("periodid"), value.GetAttribute("value")));
}
It looks like you're trying to:
Load an XmlDocument
Get a list of all the attributes of name 'periodid'
Look each periodid up using a webservice call
Return a list of the lookup results
If that is correct, the following method should do what you need:
public List<string> GetListOfData()
{
XmlDocument xmlDOC = new XmlDocument();
xmlDOC.LoadXml("<Html><value periodid='Yabba'>YabbaValue</value><value periodid='Dabba'>DabbaValue</value><value periodid='Doo'>DooValue</value></Html>"); // string storing my XML
var value = xmlDOC.GetElementsByTagName("value");
var listOfStrings = new List<string>();
for (int i = 0; i < value.Count; i++)
{
var xmlAttributeCollection = value[i].Attributes;
if (xmlAttributeCollection != null)
{
var action = xmlAttributeCollection["periodid"];
string Period1 = action.Value;
listOfStrings.Add(QPR_webService_Client.GetAttributeAsString(sessionId, Period1, "name", "") + ":" + value[i].InnerText);
}
}
return listOfStrings;
}
The content of an XDocument is the XML below.
I'd like to get a List(), see at the end of this message.
<myXml>
<myDatas code="01">
<myVar name="myvar" value="A" />
<myData name="A" value="A1" />
<myData name="B" value="B1" />
</myDatas>
<myDatas code="02">
<myVar name="myvar" value="B" />
<myData name="A" value="A2" />
<myData name="D" value="D2" />
</myDatas>
</myXml>
public class MyData
{
public string MainCode { get; set; }
public string Code { get; set; }
public string Value { get; set; }
}
I'd like a List() this content should be like this :
new MyData { MainCode = "01"; Code = "A"; Value = "A1" };
new MyData { MainCode = "01"; Code = "B"; Value = "B1" };
new MyData { MainCode = "02"; Code = "A"; Value = "A2" };
new MyData { MainCode = "02"; Code = "D"; Value = "D2" };
Sure - so you need something like this:
var query = from datas in doc.Root.Elements("myDatas")
let code = (string) datas.Attribute("code")
from data in datas.Elements("myData")
select new MyData {
MainCode = code,
Code = (string) data.Attribute("name"),
Value = (string) data.Attribute("value"),
};
var list = query.ToList();
Note the multiple from clauses to flatten the results.
Another alternative would have been to just find all the "leaf" elements and fetch the code part from the parent:
var query = from data in doc.Descendants("myData")
select new MyData {
MainCode = (string) data.Parent.Attribute("code"),
Code = (string) data.Attribute("name"),
Value = (string) data.Attribute("value"),
};
var list = query.ToList();
EDIT: If your document uses namespaces, that's easy too:
XNamespace ns = "http://the-uri-of-the-namespace";
var query = from data in doc.Descendants(ns + "myData")
...
This uses the XName operator +(XNamespace, string) overloaded operator.