C# XDocument needs to be parsed to XML again - c#

I have a Xdocument that is populated as follows:
XDocument xDoc = XDocument.Parse(new StreamReader(response.GetResponseStream()).ReadToEnd());
This gives me an XDocument that looks as follows:
<GetReportAsXMLString>
<report>
<reportItem Count ="562..................
</GetReportAsXMLStringResult>
Anything between the tag is all just a giant string(Black). How would I get this portion of the document to format as XML? The tag is also part of the string. I just don't know how to make this show it as not XML.
Thanks

It's hard to say from your description, but it looks like you'll need to first parse the response stream (valid xml), which contains another xml document (as a string). You'll need to extract the string from the 'outer' xml document and parse it into a new one:
psuedocode:
XDocument outer = response.GetResponseStream();
String innerXml = outer.Element("report").Value;
XDocument inner = XDocument.Parse(innerXml);

You have this XML content :
<GetReportAsXMLString>
<report>
<reportItem Count =\"562\"/>
<reportItem Count =\"562\"/>
</report>
</GetReportAsXMLString>
and you want to extract only the "reportItem" nodes?
If so you can do this:
string xml = "<GetReportAsXMLString><report><reportItem Count =\"562\"/><reportItem Count =\"562\"/></report></GetReportAsXMLString>";
XDocument xDoc = XDocument.Parse(xml);
IEnumerable<XElement> elList = xDoc.Descendants().Where(x => x.Name.LocalName.Equals("report")).Descendants().Where(x => x.Name.LocalName.Equals("reportItem"));

Related

How can I get a list of XML nodes by value using C#

I'm trying to get a XmlNodeList from an XmlDocument for nodes that have a certain value, with a view to removing those nodes.
XML:
<List xmlns="http://mynamespace.com/v1">
<Category>2144</Category>
<Title>My Object</Title>
<StartPrice>30.00</StartPrice>
<ReservePrice>-999</ReservePrice>
<BuyNowPrice>-999</BuyNowPrice>
</List>
Preferably I don't want to iterate through every node and check its value. I looked at trying to use LINQ from some examples but I just don't understand it enough to even attempt it.
I feel I'm getting close-ish with XPath (https://www.w3schools.com/xml/xpath_syntax.asp) but I'm beginning to think what I want to do isn't supported.
string xml = UtilityClass.SerializeObject<Listing> ( myListing);
XmlDocument xmlDocument = new XmlDocument ();
xmlDocument.LoadXml ( xml );
XmlElement root = xmlDocument.DocumentElement;
XmlNodeList nodes = root.SelectNodes ( "//*['-999']" );
Am open to other suggestions to get the same result, i.e. remove the nodes with -999 from the Xml document.
Thanks in advance
LINQ to XML is preferred API while dealing with XML in .Net Framework since 2007.
Check it out how easy to achieve what you need in one single statement.
LINQ methods are chained one after another and self-explanatory:
Get all descendants of the root node, taking into account a default namespace.
Whatever the names of the elements.
Where element value is -999.
Convert them to a List<>.
Remove those elements from the XML document.
c#
void Main()
{
XDocument xdoc = XDocument.Parse(#"<List xmlns='http://mynamespace.com/v1'>
<Category>2144</Category>
<Title>My Object</Title>
<StartPrice>30.00</StartPrice>
<ReservePrice>-999</ReservePrice>
<BuyNowPrice>-999</BuyNowPrice>
</List>");
XNamespace ns = xdoc.Root.GetDefaultNamespace();
xdoc.Descendants(ns + "List")
.Elements()
.Where(x => x.Value.Equals("-999"))
.ToList()
.ForEach(x => x.Remove());
Console.WriteLine(xdoc);
}
Output
<List xmlns="http://mynamespace.com/v1">
<Category>2144</Category>
<Title>My Object</Title>
<StartPrice>30.00</StartPrice>
</List>

c# Reading data from XML

I have problems with understandig, how to read data from XML.
XML looks like this:
<PosXML version="7.2.0">
<ReadCardResponse>
<ReturnCode>1</ReturnCode>
<Card>
<Pan>222300******5062</Pan>
<Expires>****</Expires>
<CardName>MASTERCARD</CardName>
<CardSource>2</CardSource>
</Card>
</ReadCardResponse>
</PosXML>
I have loaded XML from stream:
XDocument doc;
using (Stream responseStream = httpResponse.GetResponseStream())
{
doc= XDocument.Load(responseStream);
}
Tried this, but it's not working:
XElement returnCode = doc.XPathSelectElement("ReturnCode")
var returnCode = doc.XPathSelectElement(#"PosXML/ReadCardResponse/ReturnCode");
You need to use the full path to the element
Try:
XElement returnCode = doc.Element("ReadCardResponse").Element("ReturnCode")
You can also access elements by XPath, nodes, or some linq query. Try to play around with intellisense of your IDE

How to get value of a specific element in xml in c#

I have a xml file in below format
I want to fetch the value of Child1
When I am using below code it is providing a null value. Please help
XDocument xmlDoc = XDocument.Load(fileName);
XElement po = xmlDoc.Root.Element("Root");
XElement el1 = po.Element("Child1");
Use this:
xmlDoc.Descendants("Child1").First();

Get specific values from Xml

I don't how to extract the values from XML document, and am looking for some help as I'm new to C#
I am using XmlDocument and then XmlNodeList for fetching the particular XML document
Here is my code
XmlNodeList XMLList = doc.SelectNodes("/response/result/doc");
And my XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<result>
<doc>
<long name="LoadID">494</long>
<long name="EventID">5557</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
<doc>
<long name="LoadID">774</long>
<long name="EventID">5558</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
</result>
</response>
In this i have to fetch every the XMLData data that is under every doc tag and i have to fetch last doc tag EventID.
var xml = XDocument.Parse(xmlString);
var docs = xml.Root.Elements("doc");
var lastDocEventID = docs.Last()
.Elements("long")
.First(l => (string)l.Attribute("name") == "EventID")
.Value;
Console.WriteLine ("Last doc EventId: " +lastDocEventID);
foreach (var doc in docs)
{
Console.WriteLine (doc.Element("str").Element("TransactionDate").Value);
}
prints:
Last doc EventId: 5558
2014-05-28T14:17:31.2186777-06:00
2014-05-28T14:17:31.2186777-06:00
You can use two XPath expressions to select the nodes you want. To answer each part of your question in turn:
To select all of the XMLData nodes:
XmlNodeList XMLList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
To select the last EventId:
XmlNode lastEventIdNode =
doc.SelectSingleNode("/response/result/doc[position() =
last()]/long[#name='EventID']");
If not all doc nodes are guaranteed to have an event id child node, then you can simply:
XmlNodeList eventIdNodes =
doc.SelectNodes("/response/result/doc[long[#name='EventID']]");
XmlNode lastNode = eventIdNodes[eventIdNodes.Count - 1];
That should give you what you've asked for.
Update;
If you want the XML data inside each strXml element, you can use the InnerXml property:
XmlNodeList xmlList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
foreach(XmlNode xmlStrNode in xmlList)
{
string xmlInner = xmlStrNode.InnerXml;
}
There's one result tag short in your xml.
Try using this. It's cleaner too imho
XmlNodeList docs = doc.SelectSingleNode("response").SelectSingleNode("result").SelectNodes("doc");
Then you can use a combination of SelectSingleNode, InnerText, Value to get the data from each XmlNode in your list.
For example if you want the EventID from the first doc tag:
int eventID = int.Parse(docs[0].SelectSingleNode("long[#name='EventID']").InnerText);

JSON.NET XML to String

string json = "{"Animal":{"id":"123","verified":true}}"
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
returnXml = doc.ToString();
Why does "ReturnXml" return the following text "System.Xml.XmlDocument" and not the XML output in string format?
http://json.codeplex.com/
To print XML, you need to use InnerXml
doc.InnerXml;
The ToString method of XmlDocument is not set to output a pretty version of the xml contained therein.
You're best bet may be to just convert that XmlDocument to an XDocument, since that supports a ToString method that outputs actual XML:
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
XDocument linqXML = XDocument.Load(new XmlNodeReader(doc));
returnXML = linqXML.ToString();

Categories

Resources