how to get value(node) value from XML using asp.net c# - asp.net

<AspResp errCode="NA" errMsg="NA" status="1" transId="6c8c5901-6119-4c59-89ce-b3f9efb141f2">
<EResp errCode="NA" errMsg="NA" resCode="ea3229b1-c9ff-455b-8d3f-84a4c2384c85" status="1" ts="2020-04-27T15:00:10.947" txn="90f4f36f-7051-4c6d-bed4-bd717ddfa38d">
<Signatures>
<DocSignature error="NA" id="1">test</DocSignature>
</Signatures>
</EResp>
</AspResp>
I want value of transId from first node in the above XML.
I used this code but it is useless
foreach (XElement hashElement in doc.Descendants("transId"))
{
hashValue = (string)hashElement;
}

Select required node. Since transId is an attribute, you should access like this:
string attrtransId = node.Attributes["transId"].value

Take a look at this, It's very detailed & easy to understand.
How do I read and parse an XML file in C#?
string XMLText = #"<AspResp errCode='NA' errMsg='NA' status='1' transId='6c8c5901-6119-4c59-89ce-b3f9efb141f2'><EResp errCode='NA' errMsg='NA' resCode='ea3229b1-c9ff-455b-8d3f-84a4c2384c85' status='1' ts='2020-04-27T15:00:10.947' txn='90f4f36f-7051-4c6d-bed4-bd717ddfa38d'><Signatures><DocSignature error='NA' id='1'>test</DocSignature></Signatures></EResp></AspResp>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(XMLText);
XmlNode node = doc.GetElementsByTagName("AspResp")[0];
string transId = node.Attributes["transId"].Value;

Tested xpath with http://xpather.com/2S8920tn
string XMLText =
#"<AspResp errCode='NA' errMsg='NA' status='1' transId='6c8c5901-6119-4c59-89ce-b3f9efb141f2'><EResp errCode='NA' errMsg='NA' resCode='ea3229b1-c9ff-455b-8d3f-84a4c2384c85' status='1' ts='2020-04-27T15:00:10.947' txn='90f4f36f-7051-4c6d-bed4-bd717ddfa38d'><Signatures><DocSignature error='NA' id='1'>test</DocSignature></Signatures></EResp></AspResp>";
var doc = XDocument.Parse(XMLText);
string transId = doc.XPathSelectElement("/node()[1]").Attribute("transId")?.Value;

Related

Can we write data to a config.properties file using FileWriter and BufferedWrirter combination in a key value pair format

Using FileWriter, can I write the key value pair username = "login_data" to a .properties file instead of a .txt file?
String value1 = "This is the value from FILE WRITER";
System.out.println("Key1 == " + value1);
FileWriter fw = new FileWriter(dataFilePath, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value1);
bw.close();
To store the properties it is much better to create a Properties object, put the values and save it via store() method.
If you want to keep layout and comments too, it's worth looking at Apache Commons PropertiesConfigurationLayout:
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout();
config.setProperty("key", "value");
layout.setComment("key", "description of key");
layout.setHeaderComment("file description");
layout.save(config, new FileWriter (file));

String as xml data source in XQJ

I would like to parse my XML string using an XQJ implementation, for example, SAXON. All examples I could find refer to some database connections. Is it possible to use simple String as xml source?
Saxon has an XQJ interface, and you could either use the doc function() from XQuery e.g. :
XQDataSource ds = new SaxonXQDataSource();
XQConnection conn = ds.getConnection();
XQPreparedExpression exp = conn.prepareExpression("doc('file:/some/file.xml')/child::node()");
XQResultSequence result = exp.executeQuery();
while(result.next()) {
System.out.println(result.getItemAsString(null));
}
or directly inject in the XML into the query. e.g. -
XQDataSource ds = new SaxonXQDataSource();
XQConnection conn = ds.getConnection();
XQPreparedExpression exp = conn.prepareExpression("<a><b>test</b></a>/child::node()");
XQResultSequence result = exp.executeQuery();
while(result.next()) {
System.out.println(result.getItemAsString(null));
}
Try using
void XQExpression.bindDocument(javax.xml.namespace.QName varName, javax.xml.transform.Source value, XQItemType type)
with XQConstants.CONTEXT_ITEM as the first argument, and a StreamSource wrapping a StringReadeer as the second.

copy contents of attached file in AX 2012 to a particular record

I need to copy the contents of a attached file to a particular record in AX2012 in any form and then I have to paste this content in any string type field under same form.
I am trying to perform this as:
public void getdocucontent()
{
Dev_ManageTemplates obj_Dev_ManageTemplates;
DocuRef obj_docuRef;
DocuValue obj_DocuValue;
RecId recid;
TextIo txIoRead,
txIoWrite;
FileIOPermission fioPermission;
TextBuffer txtb;
container containFromRead;
int xx,num,
iConLength;
str sTempPath,
sFileName, completename ;
str 64 s1;
;
Dev_ManageTemplates_ds.getFirst(true);
recid = Dev_ManageTemplates.RecId;
select obj_docuRef
where obj_docuRef.RefRecId == recid;
select obj_DocuValue
where obj_DocuValue.name == obj_docuRef.Name;
sTempPath = obj_docuRef.path();
sFileName = obj_DocuValue.FileName;
completename = sTempPath+sFileName+"."+obj_DocuValue.FileType;
fioPermission = new FileIoPermission("completename",'r');
txtb = new TextBuffer();
fioPermission.assert();
txtb.fromFile("completename"); // Read text from file
//txtb.toString(); // Copy it to the clipboard
// StringEdit.text(txtb.getText());
s1 = txtb.getText();
// info(txtb.getText());
}
The error is obvious when you read the code:
new FileIoPermission("completename",'r').assert();
txtb = new TextBuffer();
txtb.fromFile("completename");
Should really be:
new FileIoPermission(completename,'r').assert();
txtb = new TextBuffer();
txtb.fromFile(completename);
Besides, the use of Hungarian Notation in AX is not Best Practice.

How do I pass in feed credentials to XDocument that allows Linq to XML to work

I can take the results of my variable xmlDoc and save it to an xml document (on disk) and the query returns results; however, when I run it live (with the code below) the query results are null.
Why is my query not working against the xmlDoc?? See screen shot below for the debug output 'xmlDoc.Root'.
There must be a cleaner way to create the XDocument??
System.Net.WebClient wc = new System.Net.WebClient();
wc.Credentials = new System.Net.NetworkCredential("bagee18#gmail.com", "my_password");
XDocument xmlDoc = XDocument.Parse(wc.DownloadString(new Uri("https://mail.google.com/mail/feed/atom")), LoadOptions.None);
var q = (from c in xmlDoc.Descendants("entry")
select new
{
name = c.Element("title").Value,
url = c.Element("link").Attribute("href").Value,
email = c.Element("author").Element("email").Value
}).ToList();
q.Dump();
xmlDoc.Root:
.
Take the namespace into account:
XNamespace df = xmlDoc.Root.Name.Namespace;
var q = (from c in xmlDoc.Descendants(df + "entry")
select new
{
name = c.Element(df + "title").Value,
url = c.Element(df + "link").Attribute("href").Value,
email = c.Element(df + "author").Element(df + "email").Value
}).ToList();

ado.net query removes file exention when adding string filename to the database

I am using the code below for saving uploaded picture and makigna thumbnail but it saves a filename without the extension to the database, therefore, I get broken links. How can I stop a strongly typed dataset and dataadapter to stop removing the file extension? my nvarchar field has nvarchar(max) so problem is not string length.
I realized my problem was the maxsize in the dataset column, not sql statement parameter, so I fixed it. You may vote to close on this question.
hasTableAdapters.has_actorTableAdapter adp1 = new hasTableAdapters.has_actorTableAdapter();
if (Convert.ToInt16(adp1.UsernameExists(username.Text)) == 0)
{
adp1.Register(username.Text, password.Text,
ishairdresser.Checked, city.Text, address.Text);
string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName;
string originalrelative = "\\pictures\\" + actorimage.FileName;
actorimage.SaveAs(originalfilename);
string thumbfilename = Server.MapPath(" ") + "\\pictures\\t_" + actorimage.PostedFile.FileName;
string thumbrelative = "\\pictures\\t_" + actorimage.FileName;
Bitmap original = new Bitmap(originalfilename);
Bitmap thumb=(Bitmap)original.GetThumbnailImage(100, 100,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
thumb=(Bitmap)original.Clone(
new Rectangle(new Point(original.Width/2,original.Height/2), new Size(100,100)),
System.Drawing.Imaging.PixelFormat.DontCare);
/*
bmpImage.Clone(cropArea,bmpImage.PixelFormat);
*/
thumb.Save(thumbfilename);
adp1.UpdatePicture(originalrelative, thumbrelative, username.Text);
LoginActor();
Response.Redirect("Default.aspx");
}
}
Looks like the problem is you are using HttpPostedFile.FileName property, which returns fully-qualified file name on the client. So, this code string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName; generates something like this:
c:\inetpub\pictures\c:\Users\Username\Pictures\image1.jpg
Use FileUpload.FileName property everywhere and you will probably get what you want.
Use this to get Image or file extension :
string Extension = System.IO.Path.GetExtension(FileUpload.FileName);

Resources