Retrieve Values manually from XML InnerXML - c#

I have been trying to deserialize the InnerXML into a class and for some reason the XML keeps changing shape and however many times I try to get the class right it seems to change shape again.
So I have given up and decided to try another method.
Is it possible to retrieve the value of a parameter within the InnerXML manually using c#?
Say for example, my XML innerXML looked like this:
<Timestamp>2014-08-22T21:45:00Z</Timestamp>
<Subscriber>https://www.dogdoza.co.uk</Subscriber>
<Order>
<OrderID>111867</OrderID>
<InvoiceNumber>DOZA-9725410</InvoiceNumber>
<CustomerID>4542</CustomerID>
Is it possible to pull out say the value of Subscriber
If this is possible I can just pull out the values I want manually. Not ideal, but there are only about 10...
I have looked around but not managed to find any code I can get working..
Can anyone please give me any guidance?
Thanks

You can do achieve what you want using LINQ to XML:
XElement myXml = XElement.Load(#"XmlLocationHere");
XElement subscriber = myXml.Descendants("Subscriber").FirstOrDefault();
XElement.Descendants returns a collection of the descendant elements for this document or element, in document order. This method will return an IEnumerable<XElement>, since there might be more than one "Subscriber" element, but in your case, we choose FirstOrDefault, which returns the first occurrence.

Try loading your XML into an XDocument. Then try to use XPathSelectElement to find the specific value you want.
It could be that you need to wrap your inner xml into a root element, because it doesn't accept multiple roots.
Pseudo example:
// set up your xml document
string xml = "<rootelement>" + myInnerXml + "</rootelement>";
XDocument doc = new XDocument();
doc.Parse(xml);
XElement subscriber = doc.XPathSelectElement("/rootelement/Subscriber");
string value = subscriber.Value;

Related

Get text from all instances of XML element using C#

I need to parse XML files where I can't predict the structure. I need to fill a string array with the inner text from every instance of the below tag no matter where they occur in the tree.
<SpecialCode>ABCD1234</SpecialCode>
Is there a simple way to accomplish this using c#?
Solution
If your XML is a string:
XDocument doc = XDocument.Parse("<SpecialCode>ABCD1234</SpecialCode>");
string[] specialCodes = doc.Descendants("SpecialCode").Select(n => n.Value).ToArray();
If your XML is a file:
XDocument doc = XDocument.Load("specialCodes.xml");
string[] specialCodes = doc.Descendants("SpecialCode").Select(n => n.Value).ToArray();
Explanation
XDocument is a handy class that allows for easy XML parsing. You'll need to add a reference to the System.Xml.Linq assembly to your project in order to use it.
The Descendents method will get all children of the XML document, which takes care of your unknown XML structure.
The Select method is a LINQ method and allows us to select a property from each node--in this case, Value.
ToArray converts the IEnumerable result from Select() to your desired result.
XmlDocument doc = new XmlDocument();
doc.Load(FILENAME);
// IN CASE OF STRING, USE FOLLOWING
//doc.LoadXml(XAML_STRING);
XmlNodeList list = doc.DocumentElement.SelectNodes("//SpecialCode");
// prefic will fetch all the SpecialCode tags from xml.

how to retrieve a particular xml tags value using c#

i need to read the value of a particular value in an xml tag, of he solutions i tried i could only find that to get a value of a tag element ,i need to traverse from root element to the child element.is there an optiion where i can directly select a tag and get its value.
In the below xml exa,i need to get 123456 value from the xml using c#.
Ex:-
<ForwardActionRequest xmlns:auth="test" xmlns="http://www.test">
<auth:Authentication>
<auth:AuthenticationData>
<auth:AuthenticationKey>test</auth:AuthenticationKey>
<auth:Username>test</auth:Username>
<auth:Password>test</auth:Password>
</auth:AuthenticationData>
</auth:Authentication>
<SearchOrderReference>
<Reference>123456</Reference>
<AllocatedBy>test</AllocatedBy>
<Description>test</Description>
</SearchOrderReference>
You can use LINQ to XML:
XDocument doc = XDocument.Load(yourXMLText);
string value = doc.Element("SearchOrderReference").Element("Reference").Value;
Please note that I haven't tested this code.
I also encourage you to read more about LINQ to XML here.
Use XmlDocument.SelectSingleNode() to pass in an XPath that will describe the node you want and then extract the value. Use this prototype as you are using namespaces:
http://msdn.microsoft.com/en-us/library/h0hw012b(v=vs.110).aspx
Read about how to instantiate an XmlNamespaceManager() and initialize it with the relevant prefix (it needs not be what you have in the xml itself), then issue the following request:
XmlNode node = doc.SelectSingleNode("/t:ForwardActionRequest/t:SearchOrderReference/t:Reference");
Given that you associate "t" with "http://www.test".
You can deserialize the xml content into a class and directly get the value of the element or you can use LINQ to XML to retrieve the element value,
XDocument doc=XDocument.Load(XMLContent or XMLPath);
string=doc.Element("SearchOrderReference").Element("Reference").Value;
From your post using VS 2005 you can try the XML Reader which reads the XML from string. Here is an example.
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
reader.ReadToFollowing("SearchOrderReference");
reader.ReadToFollowing("Reference");
string r = reader.ReadInnerXml();
}
Try following code:
XDocument doc = XDocument.Load(yourXMLText);
var node = xmlDoc.SelectSingleNode("//SearchOrderReference[#Reference='123456']");
Then extract node's attribute to get the value of reference tag.

How to get the immediate child elements of the root element using C# and XML?

<Document>
<Heading1>
<text>Heading Title</text>
<para>para1</para>
<para>para2</para>
<para>para3</para>
</Heading1>
<Heading1>
<text>2nd Heading Title</text>
<para>para4</para>
<para>para5</para>
<para>para6</para>
<Heading2>
<text>3rd Heading Title</text>
<para>para4</para>
<para>para5</para>
</Heading2>
</Heading1>
</Document>
This is XML Document. Now, i want to parse this XML file using C# (4.0). Here, I want to get all the Heading1 elements without using that element name in my program. For example, don't use document.GetElementsByTagName("Heading1");. How i get it. Guide me get out of this issue.
Thanks & Regards.
Using LINQ to XML, you can do:
var headings = yourXDocument.Root.Elements();
Using Nodes() instead of Elements() will also return text nodes and comments, which is apparently not what you want.
You can access the child elements of the document or element through the Elements() method if using LINQ to XML.
XDocument doc = ...;
var query = doc.Root.Elements();
If you're using XmlDocument, this works:
var elements = doc.SelectNodes("/*/*");
That finds all child elements of the top-level element irrespective of any of their names. It's usually safer to specify the names if you know them, so that elements with unexpected names don't get returned in your list - use /Document/Heading1 to do this.

How can I grab all the child elements in XML?

From this XML response: http://www.dreamincode.net/forums/xml.php?showuser=335389
I want to grab all of the users friends. I need to grab all of the information from the friends. Usually with the help I've been given I would use the unique ID to grab each, but since each users doesn't have the same friends it has to be dynamic and I can't hard code anything.
Would anyone please share some XDocument magic?
You can get all <user> elements in the <friends> element from the XML document like this:
var url = "http://www.dreamincode.net/forums/xml.php?showuser=335389";
var doc = XDocument.Load(url);
var friends = doc.Element("ipb").Element("profile")
.Element("friends").Elements("user");
// Or if you don't want to specify the whole path and you know that
// there is only a single element named <friends>:
var friends = doc.Descendant("friends").Elements("user");
Then you can use LINQ to process the collection. For example, to create a IEnumerable<string> with the names of all frineds, you could write:
var names = from fr in friends
select fr.Element("name").Value;
If you needed unique ID, you could read the <id> element in a similar way (if it is an integer, you could also parse it using Int32.Parse for example...)
you can probably use XPath query
http://www.w3schools.com/xpath/xpath_examples.asp
the examples uses JScript but it is also supported in .NET

Setting attributes in an XML document

I'm writing one of my first C# programs. Here's what I'm trying to do:
Open an XML document
Navigate to a part of the XML tree and select all child elements of type <myType>
For each <myType> element, change an attribute (so <myType id="oldValue"> would become <myType id="newValue">
Write this modified XML document to a file.
I found the XmlDocument.SelectNodes method, which takes an XPath expression as its argument. However, it returns an XmlNodeList. I read a little bit about the difference between an XML node and an XML element, and this seems to explain why there is no XmlNode.SetAttribute method. But is there a way I can use my XPath expression to retrieve a list of XmlElement objects, so that I can loop through this list and set the id attributes for each?
(If there's some other easier way, please do let me know.)
Simply - it doesn't know if you are reading an element or attribute. Quite possibly, all you need is a cast here:
foreach(XmlElement el in doc.SelectNodes(...)) {
el.SetAttribute(...);
}
The SelectNodes returns an XmlNodeList, but the above treats each as an XmlElement.
I am a big fan of System.Xml.Linq.XDocument and the features it provides.
XDocument xDoc = XDocument.Load("FILENAME.xml");
// assuming you types is the parent and mytype is a bunch of nodes underneath
IEnumerable<XElement> elements = xdoc.Element("types").Elements("myType");
foreach (XElement type in elements)
{
// option 1
type.Attribute("id").Value = NEWVALUE;
// option 2
type.SetAttributeValue("id", NEWVALUE);
}
Option 1 or 2 works but I prefer 2 because if the attribute doesn't exist this'll create it.
I'm sitting at my Mac so no .NET for me...
However, I think that you can cast an XmlNode to an XmlElement via an explicit cast.
You should be able to cast the XmlElement to an XmlNode then and get it's children Nodes using something like XmlNode.ChildNodes.

Categories

Resources