It is my first time posting, and I am very new to C#, so I appreciate the help. I have so many variations of this code that are close to what I need, but I can't get on my own.
I am trying to get the contents of a sub-child in an XML sting using c#. This is the sting I receive:
<?xml version="1.0" encoding="UTF-8"?>
<activation>
<activationOutput>
<AID>7706a84f-5sef5-4b49-891c-98414ebb61d5</AID>
<protectionKeyId>18305465463798407</protectionKeyId>
<activationString>encoded xml string</activationString>// What I need
</activationOutput>
<activationInput>
<activationAttribute>
<attributeName></attributeName>
<attributeValue></attributeValue>
<isvPermission></isvPermission>
<endUserPermission></endUserPermission>
</activationAttribute>
<activationAttribute>
<attributeName></attributeName>
<attributeValue></attributeValue>
</activationAttribute>
<comments></comments>
</activationInput>
</activation>
I need to get the activationString value out into a string. Having the other elements would be nice, but I only care about getting into a string v2c called. The information in between the tags is another encoded XML string.
I first bring the sting into an XML element using:
XElement rootActivation = XElement.Parse(encodedActivationResponse, LoadOptions.SetLineInfo);
What has got me stumped is how to get the sub child out as a string. Using XElement element gets me the values for all of the children under ActivationOutput, but I only need the last one.
string activationOutput = rootActivation.Element("activationOutput").Value;
It sends me a long unusable string
7706a84f-5sef5-4b49-891c-98414ebb61d518305465463798407encodedxmlstring
I've also tried:
IEnumerable<XElement> activationString = rootActivation.Elements("activationString");
It looked promising, but I don't know how to get the value out as a string. It shows as
{System.Xml.Linq.Extenstions.GetDescendantsXElement>}
I was hoping that I could take the variable and push it into a string using:
string v2c = activationString.ToString;
But that does not work either
Your attempt
string activationOutput = rootActivation.Element("activationOutput").Value;
does give you a concatenation of all the text() nodes that are children of <activationOutput>. Obviously, that's not what you want.
To solely get the <activationString>'s text() node use
string activation =
(string)rootActivation.Element("activationOutput").Element("activationString").Value;
One restriction of this approach is: it only gets the first of each elements.
If that is the only element called activationString you could just do
string activationString = XDocument.Parse("xmlFilePathHere").Descendents("activationString").FirstOrDefault().Value;
In VB.Net
Dim rootActivation As XElement
'for testing
rootActivation = <activation>
<activationOutput>
<AID>7706a84f-5sef5-4b49-891c-98414ebb61d5</AID>
<protectionKeyId>18305465463798407</protectionKeyId>
<activationString>encoded xml string</activationString>
</activationOutput>
<activationInput>
<activationAttribute>
<attributeName></attributeName>
<attributeValue></attributeValue>
<isvPermission></isvPermission>
<endUserPermission></endUserPermission>
</activationAttribute>
<activationAttribute>
<attributeName></attributeName>
<attributeValue></attributeValue>
</activationAttribute>
<comments></comments>
</activationInput>
</activation>
Dim activationString As String = rootActivation.<activationOutput>.<activationString>.Value
Related
Hello i am trying to get simple xml file from server and to read the data so i can convert it to list. I was try few lib and code with no success so far. I am getting the xml content in one line without any tags <> and the count is always 0 zero. The XML string. I need to get the data that inside camp tag
<campaigns>
<mainPage>http://example.com</mainPage>
<orderPage>https://www.example.co.il/adver/</orderPage>
<totalCount>3</totalCount>
<onLineCount>2</onLineCount>
<campaignList>
<camp id="557">
<name>test1</name>
<status>on</status>
<rating>5</rating>
<url>http://example.com/557</url>
</camp>
<camp id="559">
<name>test1</name>
<status>on</status>
<rating>5</rating>
<url>http://example.com/559</url>
</camp>
<camp id="660">
<name>test1</name>
<status>off</status>
<rating>5</rating>
<url>http://example.com/660</url>
</camp>
</campaignList>
And the c# code i am trying so far
XElement xelement = XElement.Load("http://example.com/test.xml");
var name = from nm in xelement.Elements("camp")
where (string)nm.Element("status") == "on"
select nm;
Response.Write(name.Count());
foreach (XElement xEle in name)
{
Response.Write(xEle);
}
XElement.Elements() means search in children tags. I think what you need is Descendants() or xelement.Element("campaigns").Element("campaignList").Elements("camp")
<TestCase Name="DEBUG">
<ActionEnvironment Name="Carved records indication">
<Define Name="_TestedVersionPath" Value="{CustomParam {paramName=PA tested version installer folder path}, {appName=PA installer}, {hint=\\ptnas1\builds\Temp Builds\Forensic\Physical Analyzer\PA.Test\UFED_Analyzer_17.02.05_03-00_6.0.0.128\EncryptedSetup}}"/>
<Define Name="_PathOfdata" Value="SharedData\myfolder\mydata.xml"/>
<ActionSet Name="DEBUG">
<Actions>
<SpecialAction ActionName="myactionname">
<CaseName>123</CaseName>
<UaeSendQueryValues>
<URL>192.168.75.133</URL>
<RestURL></RestURL>
<UserName>user1</UserName>
<Password>aaa</Password>
<PathOfQuery>_PathOfdata</PathOfQuery>
<Method>GET</Method>
<ParamsFromFile></ParamsFromFile>
</UaeSendQueryValues>
</SpecialAction>
</Actions>
</ActionSet>
</ActionEnvironment>
I have the above xml. i need to find every PathOfQuery tag, get the text of it (in the example _PathOfdata) and then go up in the xml tree and find the first Define tag who's name = to text of PathofQuery tag and get its value (in the example "SharedData\myfolder\mydata.xml")
then i would like to replace that value with another string.
i need to do this for each PathofQuery tag that appears in the xml (it could be more then one) and i want to find always the first apparition of the Define tag (could be more than one) when i travel the tree up from the point where the PathofQuery tag was found.
I want to do this on C Sharp
any help will be appreciated.
Let's assume string s holds the above Xml. Then the following code will work for you:
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(s);
XmlNode pathOfQuery = xDoc.SelectSingleNode("//PathOfQuery");
string pathOfQueryValue = pathOfQuery.InnerText;
Console.WriteLine(pathOfQueryValue);
XmlNode define = xDoc.SelectSingleNode("//Define[#Name='" + pathOfQueryValue + "']");
if(define!=null)
{
string defineTagValue = define.Attributes["Value"].Value;
Console.WriteLine(defineTagValue);
pathOfQuery.InnerText = defineTagValue;
Console.WriteLine(pathOfQuery.InnerText);
}
Ok, I have an xml document which is returned via a c# function and output via XSLT. In the XML document there is an encrypted string which I need to decrypt before output.
Basically, i need to run "encryptedstring" through a decrypting function in order get the real value.
XML Structure:
<root>
<order encryptedstring="676696969hjhig">
</root>
Outputting function:
XmlDocument xmlOrders = Data_Functions.Get_All_Orders();
xmlOutput.DocumentContent = xmlOrders.OuterXml;
I am assuming i need to loop through the XML document, get the value for each "encryptedstring", run that value through the decrypt function and re-inject it back into the xml document but am unsure of best way to go about that.
The decryption has to be done in the codebehind in c# by passing a string through decryptString();
With a bit of guidance from the question suggestion by #momar this was solved in the following way...
XmlNodeList aNodes = xmlOrders.SelectNodes("//root/order");
foreach (XmlNode aNode in aNodes)
{
XmlAttribute ccAttribute = aNode.Attributes["encryptedstring"];
string attValue= ccAttribute.Value;
string encKey = ConfigurationManager.AppSettings["EncryptionKey"];
string decrypt = Crypto.DecryptStringAES(attValue, encKey);
ccAttribute.Value = deencrypt;
}
xmlOutput.DocumentContent = xmlOrders.OuterXml;
I have an XML document that looks like this
<?xml version="1.0" encoding="utf-8" ?>
<event>
<name>Test Event</name>
<date>07/09/1997</date>
<description>Birthday</description>
<blogURL></blogURL>
</event>
I want to grab these fields and display them in ASP:Labels
This is my code behind
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument pressRelease = new XmlDocument();
pressRelease.Load(Server.MapPath("~/PressSection.xml"));
XmlNodeList name = pressRelease.GetElementsByTagName("name");
CurrentEventName.Text = name.ToString();
}
But this is what it displays in the label
System.Xml.XmlElementList
Not really sure what I'm doing wrong.
As the name might suggest and, as the documentation tells you, the method returns:
An XmlNodeList containing a list of all matching nodes. If no nodes match name, the returned collection will be empty.
You need to iterate that list, or simply take the first item if you're sure one will always be there:
var names = pressRelease.GetElementsByTagName("name");
CurrentEventName.Text = names[0].Value;
That said, LINQ to XML is a far nicer API, I would definitely encourage you to learn more about it:
var doc = XDocument.Load(Server.MapPath("~/PressSection.xml"));
CurrentEventName.Text = (string)doc.Descendants("name").Single();
try this way
XDocument doc = XDocument.Load(Server.MapPath("~/PressSection.xml"));
var query = doc.Descendants("event").Elements("name").FirstOrDefault();
Console.WriteLine(query.Value);
This is actually the intended behavior.
The reason for it is that it returns a list of all elements that match your criteria. If you know for sure that you'll always want the first element, you could always get the first element by:
name[0].ToString()
However, you might also want to add some null and empty checking for the XmlElementList as it may also be empty, which will result in you getting a null pointer exception if you try to get an item from it.
I am having difficulty trying to return values from an XML file. Here is an example of the XML:
<xml>
<item1>Whatever</item1>
<video>
<caption>Video Title</caption>
<width>1280</width>
<height>720</height>
</video>
<element1>Results One</element1>
<element2>Results Two</element2>
</xml>
I am calling the data like this:
XElement xmlData = XElement.Parse(e.Result);
var list = new List<VideoUrl>();
foreach (XElement item in xmlData.Elements("xml"))
{
var element1 = item.Element("element1").Value;
var element2 = item.Element("element2").Value;
list.Add(new VideoUrl
{
etc...
});
and then assigning the data to a list box to return the values. Problem is I am trying to return XML items "element1" and "element2" but nothing is returned when i run the emulator. If I change the code to return Video > Caption it works fine. I feel like its something real simple I am missing. Any ideas or code samples to fix this would be much appreciated. Thanks in advanced.
xmlData is the <xml> element, so xmlData.Elements("xml") will return no values - there are no xml elements directly under xmlData. Given that it's the root, you know there's only one node, so you can just do:
var element1 = (string) xmlData.Element("element1");
var element2 = (string) xmlData.Element("element2");
Note that by casting to string instead of using the Value property, you end up with a null reference if the element doesn't exist, instead of an exception being thrown.