Get nodes of XDocument - c#

I have this Xml
<Content xmlns="uuid:28a55566-8657-4c56-9c44-">
<Image xlink:type="simple" xlink:href="/images/" xlink:title="albums_4" xmlns:xlink="http://www.w3.org/1999/xlink"></Image>
<Title>Europe</Title>
</Content>
And I want to get each node data. The result should be for image node for example:
<Image xlink:type="simple" xlink:href="/images/" xlink:title="albums_4" xmlns:xlink="http://www.w3.org/1999/xlink"></Image>
and <Title>Europe</Title> for Title node.
My C# code:
XDocument xDoc = XDocument.Parse(Xml);
XNamespace ns = xDoc.Root.GetDefaultNamespace()
var image = xDoc.Descendants(ns + "Image").Single().Value; //it returns ""

Value property in that particular usage returns what between the Image tags, that's why you got empty string. To get XML markup of the Image node you need to call .ToString() instead :
var image = xDoc.Descendants(ns + "Image").Single().ToString();

Related

How to get value of an XML node?

For the life of me I have not been able to extract the SourcePartyName from this XML document:
<ns0:Visit xmlns:ns0="http://Co.Burgers.Ues">
<ns0:SourcePartyName>NDHARY</ns0:SourcePartyName>
</ns0:Visit>
Using Scott's solution, I've been able to extract the namespace info; however, after dozens of attempts at monkeying with XDocument / XElement, I have not been able to get the desired NDHARY value.
Attempts have included:
xdoc.Descendants(ns + "SourcePartyName").FirstOrDefault()?.Value;
and
xdoc.Element(ns + "SourcePartyName").Value;
How do you get the value of a node from an XDocument?
When using an XDocument you have to go via its Root property.
String xml = #"
<ns0:Visit xmlns:ns0=""http://Co.Burgers.Ues"">
<ns0:SourcePartyName>NDHARY</ns0:SourcePartyName>
</ns0:Visit>
";
XDocument xdoc = XDocument.Parse(xml);
XNamespace ns = "http://Co.Burgers.Ues";
String sourcePartyName = (String)xdoc.Root.Element(ns + "SourcePartyName");

Extracting data from the properties of an xml file

I am attempting to extract data from an xml file generated from a save function. Here is what the xml looks like when the data has been serialized
<Data>
<ParentID>00000000-0000-0000-0000-000000000000</ParentID>
<Content><ContentControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Grid><Image Source=".//Resources/Images/start.png" Tag="Start" ToolTip="Start" IsHitTestVisible="False" /></Grid></ContentControl> </Content>
</Data>
I can read the data between the <> signs using an XElement object and extract it value using Element("Child").Value for example the ParentID but I do not know how to extract the property data from within Content tags such as the programmatic reading the Tag property of the Image, in this case Tag='Start'.
Can someone please assist me to resolve this matter
If the problem you are running into is that the data in the Content node is a malformed fragment, then this is a way to extract that, fix the malformation and get at the data.
string asReadXml = #"<Data>
<ParentID>00000000-0000-0000-0000-000000000000</ParentID>
<Content><ContentControl xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> <Grid><Image Source="".//Resources/Images/start.png"" Tag=""Start"" ToolTip=""Start"" IsHitTestVisible=""False"" /></Grid></ContentControl> </Content>
</Data>";
var fragment = Regex.Match(asReadXml, #"(?:\<Content\>)(?<Xml>.+)(?:\</Content\>)", RegexOptions.ExplicitCapture).Groups["Xml"].Value;
var validFragment = Regex.Replace(Regex.Replace(fragment, "(<)", "<"), "(>)", ">");
var xDoc = XDocument.Parse("<Root>" + validFragment + "</Root>");
/* XDoc looks like this:
<Root>
<ContentControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Grid>
<Image Source=".//Resources/Images/start.png" Tag="Start" ToolTip="Start" IsHitTestVisible="False" />
</Grid>
</ContentControl>
</Root>
*/
var Image =
xDoc.Root
.Descendants()
.Where (p => p.Name.LocalName == "Image")
.First ();
Console.WriteLine ( Image.Attribute("Tag").Value );
// Outputs
// Start
var data = #"<Data>" +
"<ParentID>00000000-0000-0000-0000-000000000000</ParentID>" +
"<Content><ContentControl xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">"+
"<Grid><Image Source=\".//Resources/Images/start.png\" Tag=\"Start\" ToolTip=\"Start\" IsHitTestVisible=\"False\" /></Grid></ContentControl>" +
"</Content>" +
"</Data>";
var root = XElement.Parse(data);
var contentValue = root.Element("Content").Value;
var contentXml = XElement.Parse(contentValue);
var ns = contentXml.Name.Namespace; // retrieve the namespace
var imageTagValue = contentXml.Element(ns+"Grid").Element(ns+"Image").Attribute("Tag").Value; //
Assume that element is an XElement object that represent <Content> element (You already have a way to get it though), you can do as follow to get Tag attribute value of Image element :
XElement element = ....;
var content = XElement.Parse((string)element);
var ns = content.Name.Namespace;
var image = content.Descendants(ns + "Image").FirstOrDefault();
var tag = "";
if(image != null)
{
tag = (string)image.Attribute("Tag");
}
We check if image is null before looking for it's attribute. With that, you won't get exception if there any <Content> element that doesn't have <Image> element). tag variable will simply contains empty string in that case.
This also handle case when <Content> has <Image> element resides in different path (not under <Grid> element).
Personally, I would recommend getting the whole content as a string, and then parse it as a html data using http://htmlagilitypack.codeplex.com/ library. That way you'll offload all the parsing to specialized libraries.

How to get a specific XML value from an XML using C#?

I have the below XML as:
<Requests xmlResponse="true">
<Request response="yes" responsewait="120000" sequence="1" type="Fulfillment">
<RequestData>
<PrintControl>FTP</PrintControl>
<User>81DF</User>
<Documents>
<AddressChangeLetter>
<DocumentInfo>
<AddressChange AddressChangeId="109346" Branch="418" LastChangeDate="">
<Name>AAA NOVAK</Name>
<TaxID>123123121</TaxID>
<OldAddress1>BOX 216</OldAddress1>
<OldAddress2>NYANE 68017</OldAddress2>
<OldAddress3 />
<OldAddress4 />
<NewAddress1>P O BOX 216</NewAddress1>
<NewAddress2>CERESCO NE 68017</NewAddress2>
<NewAddress3 />
<NewAddress4 />
<DateChanged>05/08/2013</DateChanged>
<AccountInfo AcctNum="231232311" AcctStatusCodes="IX" />
</AddressChange>
</DocumentInfo>
</AddressChangeLetter>
</Documents>
</RequestData>
I wanted to get the name or the value which is under the tag "Documents". Since in the above XML, the tag under the "Document" tag is "AddressChangeLetter", therefore, I want to get this name. How will I do it.
Something along the lines of... (it's not perfect, but it'll get you started - Google the functions I've used to get it working properly):
XmlDocument xml = new XmlDocument();
xml.Load(yourPathGoesHere)
XmlNodeList addressNodes = xml.GetElementsByTagName("AddressChange");
foreach (XmlNode oneNode in addressNodes) {
myVariableToGrabNames = oneNode["Name"].InnerText;
}
This can be done pretty easily using Linq to XML e.g.
var xml = ...;
var xdoc = XDocument.Parse(xml);
foreach (var e in xdoc.Descendants("Documents").Elements())
{
var name = e.Name; // AddressChangeLetter
}

extracting theNamespace from the xml file

I am working on the XML files in C#.
I want to extact the name space and do some maniplations.
say my xml file looks like this.
<Content xmlns="http://ABCD.com/sdltridion/schemas/XXXXX">
<first>ABCD</first>
<second>DCEF</second>
</Content>
I want to extract Xml namespace from the root tag, ang get the value of XXXXX.
Output needed: XXXXX
Can any one help regarding this.
Thank you.
Try this:
var xdoc = XDocument.Parse(xml);
var ns = xdoc.Root.Name.Namespace.NamespaceName;
var value = new Uri(ns).Segments.LastOrDefault();
You can try XNamespace class
XNamespace ns = XNamespace.Get("http://ABCD.com/sdltridion/schemas/XXXXX");
var result = XElement.Load("URL").Descendants(ns + "NODENAME");
Thanks
Deepu

LINQ To XML Getting a value without the nodes inside

I have this XML:
<chunk type="manufacturer_info" id="" note="">test: <chunk type="style" style="link">${manufacturer_website}</chunk></chunk>
I need to get "test: " separately from the inner element.
EDIT:
This is coming into a function as an XElement.
The <chunk> element has two child nodes: a text node and a <chunk> element.
You can get the value of the text node as follows:
var element = XElement.Parse(#"<chunk type=""manufacturer_info"" ...");
var result = string.Concat(element.Nodes().OfType<XText>());
// result == "test: "
Here you go.
string xml = #"<Chunks><chunk type='manufacturer_info' id='' note=''>test: <chunk type='style' style='link'>${manufacturer_website}</chunk></chunk></Chunks>";
var xDoc = XDocument.Parse(xml);
var res = xDoc.DescendantNodes().OfType<XText>().First().Value;

Categories

Resources