How to get the xml Element having optional value minOccurs=0 - c#

Hi i need to Filter the Xml element having Optional value minOccurs=0
this is what i had Tried
var XMLDocumentMaster = XDocument.Load(#"D:\Stephen\Documents\Schema\AgileFlow_Import.xsd");
XMLDocumentM = XMLDocumentMaster();
var prefix = XMLDocumentMaster.Root.GetNamespaceOfPrefix("xs");
// get Vehicle
var vehicle = XMLDocumentMaster.Root.Element(prefix + "element");
// get sequence for Ford
var sections = vehicle.Element(prefix + "complexType")
.Element(prefix + "sequence")
// the Ford element
.Element(prefix + "element")
.Element(prefix + "complexType")
.Element(prefix + "sequence")
// elements
.Elements(prefix + "element").ToList();

Try something like this :
var XMLDocumentMaster = XElement.Load(#"D:\Stephen\Documents\Schema\AgileFlow_Import.xsd");
IEnumerable<XElement> items =
from el in XMLDocumentMaster.Descendants("minOccurs")
select el;
foreach(XElement Ovaule in items)
if(Ovaule=0)Console.WriteLine(Ovaule.Name + ":" + (string) Ovaule);

private void button2_Click(object sender, EventArgs e)
{
List<string> objdec = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"D:\Stephen\Documents\Schema\AgileFlow_Import.xsd");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
XmlNodeList nodes = xmlDoc.SelectNodes("//xs:element[#name='IR_DocumentMaster']//xs:complexType//xs:all//xs:element", nsmgr);
try
{
objdec = nodes.Cast<XmlNode>().Where(node => node.Attributes.GetNamedItem("minOccurs") != null && node.Attributes.GetNamedItem("minOccurs").Value == "0")
.Select(x => x.Attributes["name"].Value).ToList();

Related

XML to string (C#)

I have a XML loaded from a URL like this:
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
try
{
string reply = client.DownloadString("http://Example.com/somefile.xml");
label1.Text = reply;
}
catch
{
label1.Text = "FAILED";
}
That XML belongs to a RSS Feed. I want that label1.Text shows just the titles of that XML. How can I achieve that?
Example of label1.Text
This is my first title - This is my 2nd title - And this is my last title
You can load your XML into an XmlDocument and then use XPath to Get the value of each node you're targeting.
XmlDocument doc = new XmlDocument();
doc.LoadXml(reply);
XmlNodeList nodes = doc.SelectNodes("//NodeToSelect");
foreach (XmlNode node in nodes)
{
//If the value you want is the content of the node
label1.Text = node.InnerText;
//If the value you want is an attribute of the node
label1.Text = node.Attributes["AttibuteName"].Value;
}
If you are not familiar with XPath you can always check here :
http://www.w3schools.com/xpath/xpath_syntax.asp
var xml= XElement.Parse(reply);
label1.Text = string.Join(Environment.NewLine, xml
.Descendants()
.Where (x => !string.IsNullOrEmpty(x.Value))
.Select(x=> string.Format("{0}: {1}", x.Name, x.Value))
.ToArray());
You probably need to parse the RSS XML manually to get the title. Here is some sample code for your reference:
private static List<FeedsItem> ParseFeeds(string feedsXml)
{
XDocument xDoc = XDocument.Parse(feedsXml);
XNamespace xmlns = "http://www.w3.org/2005/Atom";
var items = from entry in xDoc.Descendants(xmlns + "entry")
select new FeedsItem
{
Id = (string)entry.Element(xmlns + "id").Value,
Title = (string)entry.Element(xmlns + "title").Value,
AlternateLink = (string)entry.Descendants(xmlns + "link").Where(link => link.Attribute("rel").Value == "alternate").First().Attribute("href").Value
};
Console.WriteLine("Count = {0}", items.Count());
foreach(var i in items)
{
Console.WriteLine(i);
}
return null;
}

Parsing XML - Value out of range

I have a problem, I am trying to list all my tfs projects and I am having this exception:
Value does not fall within the expected range.
Here is my method
public async Task<XElement> Deserialize()
{
string xml = "https://tfsodata.visualstudio.com/DefaultCollection/Projects('xxxx')/WorkItems";
var feed = await this.GetAsync(PROJECTS_PATH);
var x = feed.Items.ToString();
XElement dataTfs = new XElement(x);
foreach(var tfsdata in feed.Items)
{
var xDoc = XDocument.Parse(tfsdata.Content.Text);
IEnumerable<XElement> elem = xDoc.Elements();
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
var data = from query in xDoc.Descendants(m + "properties")
select new TfsEntities.Models.TfsEntities.properties
{
Title = (string)query.Element(d + "Title"),
State = (string)query.Element(d + "State"),
Reason = (string)query.Element(d + "Reason")
};
dataTfs.Add(data.ToList());
}
return (XElement)dataTfs;
}
Does anyone know how to fix this problem please?
Thank you

Loop through XML with XmlDocument

I'm new to using Linq and XMLDocument.
I have a simple XML file and I want to loop through all of the elements and print the tag and value. I don't want to use the XML Tags when looping through. this is what I have so far.
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<Step1>One
<Step2>Two
<Step3>Three
<Step4>Four
</Step4>
</Step3>
</Step2>
</Step1>
C# Code
private void StartIt()
{
System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.Load(#"C:\Projects\GetXML\testLayers.xml");
XmlNodeList nl = xd.SelectNodes("Layer1");
foreach (XmlNode xnode in nl)
{
Console.WriteLine(xnode.Name + " = " + xnode.InnerText); // + " " + xnode.InnerXml);
}
}
Results:
Step1 = One
Two
Three
Four
What I want:
Step1 = One
Step2 = Two
Step3 = Three
Step4 = Four
Any suggestions?
With a little help of Linq,
XmlDocument doc = new XmlDocument();
doc.Load(fname);
var nodes = doc.SelectNodes("//*[text()]")
.Cast<XmlNode>()
.Select(n => new {
Name= n.Name,
Value = n.SelectSingleNode("text()").Value
})
.ToList();
// System.Xml.XmlDocument version
XmlDocument xd = new XmlDocument();
xd.Load(#"C:\Projects\GetXML\testLayers.xml");
foreach (XmlElement step in xd.SelectNodes("//*"))
{
Console.WriteLine("{0} = {1}", step.Name,
step.SelectSingleNode("text()").Value);
}
// System.Xml.Linq.XDocument version
XDocument xdLinq = XDocument.Load(#"C:\Projects\GetXML\testLayers.xml");
foreach (XElement step in xdLinq.XPathSelectElements("//*"))
{
Console.WriteLine("{0} = {1}", step.Name,
step.Nodes().Where(n => n.NodeType == XmlNodeType.Text).FirstOrDefault());
}
You can do the same using LINQ to XML and XDocument class:
var xDoc = XDocument.Load("Input.txt");
foreach (var e in xDoc.Descendants())
{
Console.WriteLine("{0} = {1}", e.Name, e.Nodes().OfType<XText>().First().Value.Trim());
}

Extracting data from a complex XML with LINQ

My goal is to save the data contained in the ValueReference node, TimeInstant attribute, and timePosition node into variables. I am able to get the value of the valueReference node (the un-commented section works), but not the other two.
Any help would be greatly appreciated.
Here is the code that I am working on:
public void LinqToXml()
{
XNamespace sosNamespace = XNamespace.Get("http://www.opengis.net/sos/2.0");
XNamespace fesNamespace = XNamespace.Get("http://www.opengis.net/fes/2.0");
XNamespace gmlNamespace = XNamespace.Get("http://www.opengis.net/gml/2.0");
var root = XElement.Load(#"C:\Working Directory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
var a = (from level in root.Descendants(sosNamespace + "temporalFilter")
select new
{
valueReference = (string)level.Descendants(fesNamespace + "After")
.Elements(fesNamespace + "ValueReference")
.First(),
/*timeInstant = (string)level.Descendants(fesNamespace + "After")
.Elements(gmlNamespace + "TimeInstant")
.Attributes(gmlNamespace + "id")
.First()*/
/*timePosition = (string)level.Descendants(fesNamespace + "After")
.Elements(gmlNamespace + "TimeInstant")
.First()*/
}).ToList();
And here is the XML I am trying to read:
<?xml version="1.0" encoding="UTF-8"?>
<sos:GetObservation xmlns="http://www.opengis.net/sos/2.0" service="SOS" version="2.0.0"
xmlns:sos="http://www.opengis.net/sos/2.0" xmlns:fes="http://www.opengis.net/fes/2.0"
xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:swe="http://www.opengis.net/swe/2.0"
xmlns:swes="http://www.opengis.net/swes/2.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sos/2.0
http://schemas.opengis.net/sos/2.0/sos.xsd">
<!--identifier of an offering-->
<offering>HG.Logger#DJK001</offering>
<!--identifier of an observed property-->
<observedProperty>HG</observedProperty>
<!--optional temporal filter restricting the results which shall be returned-->
<temporalFilter>
<fes:After>
<fes:ValueReference>phenomenonTime</fes:ValueReference>
<gml:TimeInstant gml:id="startPosition">
<gml:timePosition>2008-03-01T17:44:15.000+00:00</gml:timePosition>
</gml:TimeInstant>
</fes:After>
</temporalFilter>
<featureOfInterest>DJK001</featureOfInterest>
</sos:GetObservation>
Your gml namespace is not correct, after changing it to
XNamespace gmlNamespace = XNamespace.Get("http://www.opengis.net/gml/3.2");
you can use
timeInstant = level.Descendants(fesNamespace + "After")
.First()
.Element(gmlNamespace + "TimeInstant")
.Attribute(gmlNamespace + "id")
.Value,
timePosition = level.Descendants(fesNamespace + "After")
.First()
.Element(gmlNamespace + "TimeInstant")
.Value
You should do it like this
XNamespace sosNamespace = "http://www.opengis.net/sos/2.0";
XNamespace fesNamespace = "http://www.opengis.net/fes/2.0";
XNamespace gmlNamespace = "http://www.opengis.net/gml/3.2";
//you had used 2.0 instead of 3.2
var root = XElement.Load(#"C:\WorkingDirectory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
var yourList=root.Descendants(sosNamespace+"temporalFilter").Descendants(fesNamespace+"After").Select(x=>
new
{
ValueReference=x.Element(fesNamespace+"ValueReference").Value,
timeInstant=x.Element(gmlNamespace+"TimeInstant").Attribute(gmlNamespace+"id").Value,
timePosition=x.Element(gmlNamespace+"TimeInstant").Element(gmlNamespace+"timePosition").Value
}
);
yourList contains all the data
you can also use good old XPath
var doc = new XPathDocument("1.xml");
var nav = doc.CreateNavigator();
var mng = new XmlNamespaceManager(nav.NameTable);
mng.AddNamespace("sos", "http://www.opengis.net/sos/2.0");
mng.AddNamespace("fes", "http://www.opengis.net/fes/2.0");
mng.AddNamespace("gml", "http://www.opengis.net/gml/3.2");
var valueReference = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/fes:ValueReference[1]", mng).TypedValue;
var TimeInstant = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/gml:TimeInstant/#gml:id", mng).TypedValue;
var timePosition = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/gml:TimeInstant/gml:timePosition[1]", mng).TypedValue;
TRY THIS CODE:
XmlDocument xmlSnippet = new XmlDocument();
xmlSnippet.Load(#"C:\Working Directory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
//Selects all the similar nodes by tag Name.......
XmlNodeList xmlSnippetNodes = xmlSnippet.GetElementsByTagName("fes:After");
//Checking if any any xmlSnippetNode has matched.
if (xmlSnippetNodes != null)
{
//Checks if the matched xmlSnippetNode that has fes:After attribute is not NULL
//Stores the value of the matched tag.
var valueReference= xmlSnippetNodes.Item(0).Value;
var timeInstance=xmlSnippetNodes.Item(1).Attributes["gml:id"].Value;
var timePosition =xmlSnippetNodes.Item(1).InnerXml.Name;
//Return True if updated correctly.
isUpdated = true;
}

Selecting Soap XML node children in .net

I have the following SOAP response:
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header/>
<env:Body>
<GetSalesResponse xmlns="http://api.dgm-uk.com/Publisher/schemas">
<status>ok</status>
-<sales>
-<sale>
<saleid>***</saleid>
<campaignname>***</campaignname>
<campaignid>***</campaignid>
<advertisername>***</advertisername>
</sale>
-<sale>
<saleid>***</saleid>
<campaignname>***</campaignname>
<campaignid>***</campaignid>
<advertisername>***</advertisername>
</sale>
..............etc
Now, I was able to get all the sale elements using this code:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlFile.NameTable);
nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("GSR", "http://api.dgm-uk.com/Publisher/schemas");
var items = xmlFile.DocumentElement.SelectSingleNode("/soapenv:Envelope/soapenv:Body/GSR:GetSalesResponse/GSR:sales", nsmgr);
How can I then while iterating the sale elements, select their inner children like saleid and campaignid? I just can't select them
This works...
XElement doc = XElement.Load("c:\\dd.xml");
XNamespace ns1 = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace ns2 = "http://api.dgm-uk.com/Publisher/schemas";
var items = doc.Descendants(ns1 + "Body").Descendants(ns2 + "GetSalesResponse").Descendants(ns2 + "sales").Descendants(ns2 + "sale")
.Select((x) => new
{
saleid = x.Element(ns2 + "saleid").Value,
campaignname = x.Element(ns2 + "campaignname").Value,
campaignid = x.Element(ns2 + "campaignid").Value,
advertisername = x.Element(ns2 + "advertisername").Value
});
foreach (var itm in items)
{
Console.WriteLine("saleid:" + itm.saleid);
Console.WriteLine("campaignid:" + itm.campaignid);
Console.WriteLine("campaignname:" + itm.campaignname);
Console.WriteLine("advertisername:" + itm.advertisername);
}

Categories

Resources