c# parsing xml again with XDocument - c#

I have looked at a lot of help files and a lot of similar questions to mine but I am not able to get further than returning the descendant collection.
What I want to achieve is to get an array that contains the values of all the id attributes of the tag elements that have ph or bpt children (not those that have st) in the XPath of xliff\file\header\tag-defs
Here is the xml. I stripped out other tags and it is truncated after the header element, for simplicity:
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns:sdl="http://sdl.com/FileTypes/SdlXliff/1.0" version="1.2" sdl:version="1.0" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file original="\\txl-app1\scncontent\AUDIO\en\Testing\SubtitleXML-FTS\13Mar16_Game.xml" source-language="en-US" datatype="x-sdlfilterframework2" target-language="da-DK">
<header>
<reference>
<internal-file form="base64"></internal-file>
</reference>
<sdl:ref-files>
<sdl:ref-file uid="0" id="http://www.sdl.com/Sdl.FileTypeSupport.Native.Xml/OriginalXmlFile" name="DF44_13Mar16_Speech_BirthdayGame.xml" o-path="\\txl-app1\scncontent\AUDIO\en\Testing\SubtitleXML-FTS\13Mar16_Speech_BirthdayGame.xml" date="04/25/2016 18:55:53" descr="The original XML file." expected-use="Generation" />
</sdl:ref-files>
<file-info xmlns="http://sdl.com/FileTypes/SdlXliff/1.0">
<value key="SDL:FileId">c6550fcb-8e69-428a-a0a8-6447918a97a2</value>
<value key="SDL:CreationDate">04/25/2016 16:16:55</value>
<value key="SDL:OriginalFilePath">\\txl-app1\content\Testing\SubtitleXML-FTS\13Mar16_Game.xml</value>
<value key="SDL:InputFilePath">\\txl-app1\content\en\Testing\SubtitleXML-FTS\13Mar16_Game.xml</value>
<value key="SDL:OriginalEncoding">utf-8</value>
<value key="HasUtf8Bom">true</value>
<value key="IsFragment">false</value>
<value key="SchemaLocation"></value>
<value key="SDL:AutoClonedFlagSupported">True</value>
<value key="xmlDeclaration">true</value>
<value key="SDLWS:AssetId">1489743</value>
<value key="SDLWS:DocId">3043144</value>
<value key="SDLWS:TaskId">1382715</value>
<value key="SDLWS:ScopingMode">0</value>
<value key="SDLWS:CreationDate">2016-04-26T00:16:55Z</value>
<value key="SDLWS:ProjectName">SubtitleXML-FTS_da_DK_20160425_111419</value>
<value key="SDLWS:UserName">BI</value>
<value key="ParagraphTextDirections"></value>
<sniff-info>
<detected-encoding detection-level="Certain" encoding="utf-8" />
<detected-source-lang detection-level="Guess" lang="en-US" />
<props>
<value key="HasUtf8Bom">true</value>
<value key="IsFragment">false</value>
<value key="SchemaLocation"></value>
<value key="xmlDeclaration">true</value>
</props>
</sniff-info>
</file-info>
<sdl:filetype-info>
<sdl:filetype-id>Custom XML v 1.2.0.0 (WS:SubtitleXML-FTS)</sdl:filetype-id>
</sdl:filetype-info>
<fmt-defs xmlns="http://sdl.com/FileTypes/SdlXliff/1.0">
<fmt-def id="1">
<value key="Italic">True</value>
<value key="TextColor">Black</value>
</fmt-def>
</fmt-defs>
<tag-defs xmlns="http://sdl.com/FileTypes/SdlXliff/1.0">
<tag id="7">
<bpt name="i" seg-hint="Include" word-end="false"><i></bpt>
<ept name="i" word-end="false"></i></ept>
<fmt id="1" />
</tag>
<tag id="3">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:00:08 01:05:04:26" WidthAllowed="75"/></ph>
</tag>
<tag id="4">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:05:00 01:05:08:24" WidthAllowed="60"/></ph>
</tag>
<tag id="5">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:08:28 01:05:13:04" WidthAllowed="60"/></ph>
</tag>
<tag id="6">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:13:08 01:05:17:22" WidthAllowed="60"/></ph>
</tag>
<tag id="8">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:17:26 01:05:22:11" WidthAllowed="60"/></ph>
</tag>
<tag id="9">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:21:21 01:05:27:13" WidthAllowed="90"/></ph>
</tag>
<tag id="10">
<ph name="Sub" seg-hint="Include"><Sub tc="01:05:27:17 01:05:33:02" WidthAllowed="75"/></ph>
</tag>
<tag id="13">
<ph name="zwnj" word-end="false" seg-hint="Include"><zwnj dir="1" spc="20"/></ph>
</tag>
<tag id="16">
<ph name="Sub" seg-hint="Include"><Sub tc="01:41:20:04 01:41:21:24" WidthAllowed="30"/></ph>
</tag>
<tag id="0">
<st><XMLsubtitlefile"></st>
</tag>
<tag id="1">
<st><Subtitles></st>
</tag>
<tag id="2">
<st><NonVOsubs></st>
</tag>
<tag id="11">
<st></NonVOsubs></st>
</tag>
<tag id="12">
<st><VOsub tc="01:41:01:17 01:41:09:27" WidthAllowed="120"></st>
</tag>
<tag id="14">
<st></VOsub></st>
</tag>
<tag id="15">
<st><NonVOsubs></st>
</tag>
<tag id="17">
<st></NonVOsubs></st>
</tag>
<tag id="18">
<st></Subtitles></st>
</tag>
<tag id="19">
<st></XMLsubtitlefile></st>
</tag>
</tag-defs>
</header>
<body>...
Code-wise I tried different versions, but this is where I am at:
private static XDocument xliff;
public static List<XElement> GetTagArray(string FilePath)
{
xliff = XDocument.Load(Path.GetFullPath(FilePath));
XNamespace ns = "http://sdl.com/FileTypes/SdlXliff/1.0";
var elements = xliff.Descendants().Elements(ns + "tag-defs").Elements().Select(e => e.Elements(ns + "ph")).ToList();
//and here I am stuck as not matter what I do above it returns empty...
}
Thank you for any help in advance.

Untested code, but try something like the following:
XNamespace sdl = #"http://sdl.com/FileTypes/SdlXliff/1.0";
XNamespace ns = #"urn:oasis:names:tc:xliff:document:1.2";
foreach (var tag in xliff.Descendants(sdl + "tag"))
{
foreach (var ph in tag.Elements(sdl + "ph"))
{
// Code here to process
}
}

The solution with help from Jesse Good is:
private static XDocument xliff;
public static int[] GetTagArray(string FilePath)
{
xliff = XDocument.Load(Path.GetFullPath(FilePath));
XNamespace ns = "http://sdl.com/FileTypes/SdlXliff/1.0";
int[] elements = xliff.Descendants().Elements(ns + "tag-defs").Elements(ns + "tag").Elements(ns + "ph").Select(e => Int32.Parse(e.Parent.Attribute("id").Value)).ToArray();
int[] elements2 = xliff.Descendants().Elements(ns + "tag-defs").Elements(ns + "tag").Elements(ns + "bpt").Select(e => Int32.Parse(e.Parent.Attribute("id").Value)).ToArray();
int[] intarray = elements.Concat(elements2).ToArray();
Array.Sort(intarray);
return intarray;
}

Related

Parsing XML Document in C#

I am writing a C# code to parse the following XML doc :
<?xml version="1.0" encoding="utf-8" ?>
<teams>
<team id="1">
<name>RealMadrid</name>
<players>
<player id="1" role="Forward">
<firstname>Cristiano</firstname>
<lastname>Ronaldo</lastname>
<number>7</number>
</player>
<player id="2" role="Forward">
<firstname>Gareth</firstname>
<lastname>Bale</lastname>
<number>11</number>
</player>
<player id="3" role="Midfield">
<firstname>Toni</firstname>
<lastname>Kroos</lastname>
<number>8</number>
</player>
<player id="4" role="Midfield">
<firstname>Luka</firstname>
<lastname>Modric</lastname>
<number>19</number>
</player>
<player id="5" role="Defence">
<firstname>Sergio</firstname>
<lastname>Ramos</lastname>
<number>4</number>
</player>
<player id="6" role="Defence">
<firstname>Raphael</firstname>
<lastname>Varane</lastname>
<number>2</number>
</player>
<player id="7" role="Goalkeeper">
<firstname>Keylor</firstname>
<lastname>Navas</lastname>
<number>1</number>
</player>
</players>
</team>
<team id="2">
<name>Barcelona</name>
<players>
<player id="1" role="Forward">
<firstname>Lionel</firstname>
<lastname>Messi</lastname>
<number>10</number>
</player>
<player id="2" role="Forward">
<firstname>Neymar</firstname>
<lastname>Jr.</lastname>
<number>11</number>
</player>
<player id="3" role="Midfield">
<firstname>Ivan</firstname>
<lastname>Rakitic</lastname>
<number>4</number>
</player>
<player id="4" role="Midfield">
<firstname>Andres</firstname>
<lastname>Iniesta</lastname>
<number>8</number>
</player>
<player id="5" role="Defence">
<firstname>Gerard</firstname>
<lastname>Pique</lastname>
<number>3</number>
</player>
<player id="6" role="Defence">
<firstname>Javier</firstname>
<lastname>Mascherano</lastname>
<number>14</number>
</player>
<player id="7" role="Goalkeeper">
<firstname>Andre</firstname>
<lastname>Ter Stegen</lastname>
<number>1</number>
</player>
</players>
</team>
<team id="3">
<name>Liverpool</name>
<players>
<player id="1" role="Forward">
<firstname>Daniel</firstname>
<lastname>Sturridge</lastname>
<number>15</number>
</player>
<player id="2" role="Forward">
<firstname>Roberto</firstname>
<lastname>Firmino</lastname>
<number>11</number>
</player>
<player id="3" role="Midfield">
<firstname>Philippe</firstname>
<lastname>Coutinho</lastname>
<number>10</number>
</player>
<player id="4" role="Midfield">
<firstname>Adam</firstname>
<lastname>Lallana</lastname>
<number>20</number>
</player>
<player id="5" role="Defence">
<firstname>Joel</firstname>
<lastname>Matip</lastname>
<number>32</number>
</player>
<player id="6" role="Defence">
<firstname>Dejan</firstname>
<lastname>Lovren</lastname>
<number>6</number>
</player>
<player id="7" role="Goalkeeper">
<firstname>Simon</firstname>
<lastname>Mignolet</lastname>
<number>22</number>
</player>
</players>
</team>
</teams>
I want to write the firstname and lastname for players of a specific team.
I wrote the following code :
var realTeam = from db in xelement.Elements("team")
where (string)db.Element("name")=="RealMadrid"
select db;
//Console.WriteLine("Real Madrid");
foreach (var e in realTeam)
{
Console.WriteLine(e);
}
This code is giving all the xml part related to "RealMadrid".
What should I do write on the firstname and lastname of this part?
Any help is appreciated!!
Do it like this:
var xmlContent = "YOUR XML";
var xmlDoc = XDocument.Parse(xmlContent);
var realTeamName = "RealMadrid";
var realTeam = from team in xmlDoc.Elements("teams")
.Descendants("team")
where team.Element("name").Value == realTeamName
select team;
var players = realTeam.Elements("players").Elements(); // get players
foreach (var player in players) // iterate over players
{
Console.WriteLine("First name: " + player.Element("firstname").Value);
Console.WriteLine("Last name: " + player.Element("lastname").Value);
}
So far you've got the team, but now you need to step into the team elements to get the players list and then the single player with firstname, lastname....
As I mentioned in my comment, you're not selecting the players element in your statement. Try the following:
var realTeam = from db in xelement.Elements("team")
where (string)db.Element("name")=="RealMadrid"
select db.Elements("players");
//Console.WriteLine("Real Madrid");
if (realTeam.Count() != 1)
{
//more than 1 team called RealMadrid was found, handle this case here
return;
}
foreach (var e in realTeam.Single())
{
Console.WriteLine("First Name: " + e.Element("firstname").Value); //or e.Element("firstname").ToString()
Console.WriteLine("Last Name: " + e.Element("lastname").Value);
}

Error in the document XML (2, 454) tryind to convert object to xml

I´m trying get data from a Web Service using c# my procedure is convert the object to a XML like this
private void btnLecturaBLur_Click(object sender, EventArgs e)
{
//get the web service method
recibodlxService service = new recibodlxService();
// Convert the Xml from object
string sXml = GetXMLFromObject(service.Controlrecibo());
this is how i get the XML from an Object..
public static string GetXMLFromObject(object o)
{
StringWriter sw = new StringWriter();
XmlTextWriter tw = null;
try
{
XmlSerializer serializer = new XmlSerializer(o.GetType());
tw = new XmlTextWriter(sw);
serializer.Serialize(tw, o);
}
catch (Exception ex)
{
//Handle Exception Code
}
finally
{
sw.Close();
if (tw != null)
{
tw.Close();
}
}
return sw.ToString();
}
and this is the XML from the web service
<SOAP-ENV:Envelope SOAP-
ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-
ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://blutest.blulogistics.net/LFA/confirmRcv3.php"
xmlns:ns2="http://xml.apache.org/xml-soap" xmlns:SOAP-
ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:ControlreciboResponse>
<return SOAP-ENC:arrayType="ns2:Map[6]" xsi:type="SOAP-ENC:Array">
<item xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">OCN</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:int">39147</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">codigo</key>
<value xsi:type="xsd:string">17429</value>
</item>
<item>
<key xsi:type="xsd:string">Cantidad</key>
<value xsi:type="xsd:int">12</value>
</item>
<item>
<key xsi:type="xsd:string">Estatus</key>
<value xsi:type="xsd:string">Disponible</value>
</item>
</value>
</item>
</value>
</item>
</item>
<item xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">OCN</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:int">39147</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">codigo</key>
<value xsi:type="xsd:string">32757</value>
</item>
<item>
<key xsi:type="xsd:string">Cantidad</key>
<value xsi:type="xsd:int">13</value>
</item>
<item>
<key xsi:type="xsd:string">Estatus</key>
<value xsi:type="xsd:string">Disponible</value>
</item>
</value>
</item>
</value>
</item>
</item>
<item xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">OCN</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:int">39147</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">codigo</key>
<value xsi:type="xsd:string">48156</value>
</item>
<item>
<key xsi:type="xsd:string">Cantidad</key>
<value xsi:type="xsd:int">6</value>
</item>
<item>
<key xsi:type="xsd:string">Estatus</key>
<value xsi:type="xsd:string">Disponible</value>
</item>
</value>
</item>
</value>
</item>
</item>
<item xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">OCN</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:int">39147</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">codigo</key>
<value xsi:type="xsd:string">52314</value>
</item>
<item>
<key xsi:type="xsd:string">Cantidad</key>
<value xsi:type="xsd:int">7</value>
</item>
<item>
<key xsi:type="xsd:string">Estatus</key>
<value xsi:type="xsd:string">Disponible</value>
</item>
</value>
</item>
</value>
</item>
</item>
<item xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">OCN</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:int">39147</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">codigo</key>
<value xsi:type="xsd:string">55327</value>
</item>
<item>
<key xsi:type="xsd:string">Cantidad</key>
<value xsi:type="xsd:int">10</value>
</item>
<item>
<key xsi:type="xsd:string">Estatus</key>
<value xsi:type="xsd:string">Disponible</value>
</item>
</value>
</item>
</value>
</item>
</item>
<item xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">OCN</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:int">39147</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">codigo</key>
<value xsi:type="xsd:string">57813</value>
</item>
<item>
<key xsi:type="xsd:string">Cantidad</key>
<value xsi:type="xsd:int">6</value>
</item>
<item>
<key xsi:type="xsd:string">Estatus</key>
<value xsi:type="xsd:string">Disponible</value>
</item>
</value>
</item>
</value>
</item>
</item>
</return>
</ns1:ControlreciboResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
the error that is shows me is Error in the document XML (2, 454)

How to parse XML file in c#

I have a XML that has a structure similar to this one:
<?xml version="1.0" encoding="UTF-8"?>
<CompanyName>
<AttrContainer>
<Attr type="String">
<Name value="'Name'" />
<Value value="'AttrContainer'" />
</Attr>
<SubContainer>
<AttrContainer value="'WSSMetadata'" />
<AttrContainer>
<Attr type="String">
<Name value="'Name'" />
<Value value="'AttrContainer'" />
</Attr>
<SubContainer>
<WSSMetadata value="'afe2e194-0ce7-4bfc-b446-9623e4fe7189'" />
<AttrContainer>
<Attr type="String">
<Name value="'Name'" />
<Value value="'WSSMetadata'" />
</Attr>
<Attr type="Uuid">
<Name value="'scanID'" />
<Value value="afe2e194-0ce7-4bfc-b446-9623e4fe7189" />
</Attr>
<Attr type="String">
<Name value="'imagePath'" />
</Attr>
<Attr type="String">
<Name value="'imagePathHD'" />
</Attr>
<Attr type="String">
<Name value="'imagePathThumbnail'" />
</Attr>
<Attr type="String">
<Name value="'imagePathGrey'" />
<Value value="'Images/afe2e194-0ce7-4bfc-b446-9623e4fe7189_grey.jpg'" />
</Attr>
<Attr type="String">
<Name value="'imagePathGreyHD'" />
<Value value="'Images/afe2e194-0ce7-4bfc-b446-9623e4fe7189_grey_hd.jpg'" />
</Attr>
<Attr type="String">
<Name value="'imagePathGreyThumbnail'" />
<Value value="'Images/afe2e194-0ce7-4bfc-b446-9623e4fe7189_grey_thumbnail.jpg'" />
</Attr>
</AttrContainer>
</SubContainer>
</AttrContainer>
</SubContainer>
</AttrContainer>
</CompanyName>
and I am trying to parse it using this code (Linq to XML)
var xmlContent = File.ReadAllText(filePathName);
var doc = XDocument.Parse(xmlContent);
var attr = doc.Root.Elements("CompanyName");
var x = attr.ToList();
but it x has no element.
My questions:
What is wrong with this code that I am not able to get the CompanyName element?
How can I get list of all <SubContainer> elements?
When I got the list of <SubContainer> elements, how can I read read and change its content?
I think you want this instead:
var attr = doc.Root.Elements("AttrContainer");
.Elements returns child elements of that name. CompanyName is you root node, and you're trying to search for its children which are AttrContainer.
What is wrong with this code that I am not able to get the companyname element?
The root element of your xml is CompanyName. So what your code is doing, it's essentially asking 'give me all CompanyName elements that are children of my root CompanyName element'. Hence the list is empty.
how can I get list of all SubContainer elements.
You can use
var subContainers = doc.Root.Descendants("SubContainer");
when I got the list of SubContainer elements, how can I read read and change its content?
foreach (var subContainer in subContainers)
{
foreach (var attrContainer in subContainer.Elements("AttrContainer"))
{
var attr = attrContainer.Elements("Attr").FirstOrDefault();
if (attr != null)
{
var oldValue = attr.Attribute("type").Value;
attr.Attribute("type").Value = "something completely different";
}
}
}
This reads and changes the type on each first Attr element (assuming one exists) in all AttrContainers in all SubContainers - hopefully you can derive something meaningful out of that.
doc.Root returns the element <CompanyName>, so further selecting elements named CompanyName won't return any elements. You're effectively trying to select all <CompanyName> elements that are children of <CompanyName>.
This code will select all <SubContainer> elements no matter their depth. I'm suggesting this because your example XML has several <SubContainer> elements.
// Read all Attr elements
IEnumerable<XElement> subContainerElements = doc.Root.Descendants("SubContainer");
foreach (XElement subContainerElement in subContainerElements)
{
// Work with <SubContainer> element here
}

XML extracting attributes using XMLDocument

i am trying to parse an xml element using XMLDocument (DItem >> Title)
below is my code but somehow i am not getting hold of it.... any help?
XmlDocument xmldoc = new XmlDocument();
XmlNamespaceManager xmlns = new XmlNamespaceManager(xdoc.NameTable);
xmlns.AddNamespace("DItems", "http://namespace.xsd");
xmldoc.Load(url);
var title = xmldoc.SelectNodes("content", xmlns);
foreach (XmlNode node in title)
{
string title = node.Attributes["Title"].Value;
//this.ddlTitle.Items.Add(new ListItem(title));
}
here is my XML:
<?xml version='1.0'?>
<root xmlns="http://www.w3.org/2005/Atom">
<title type="text">title</title>
<entry>
<content type="application/xml">
<Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd">
<CatalogSource Acronym="ABC" OrganizationName="organization name" />
<Item Id="28466" CatalogUrl="url">
<DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title1">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
<entry>
<content type="application/xml">
<Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd">
<CatalogSource Acronym="ABC" OrganizationName="organization name" />
<Item Id="28466" CatalogUrl="url">
<DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title2">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
<entry>
<content type="application/xml">
<Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.namespace.xsd">
<CatalogSource Acronym="ABC" OrganizationName="organization name" />
<Item Id="28466" CatalogUrl="url">
<DItem xmlns:content="http://namespace.xsd" TargetUrl="http://index.html" Title="my title3">
<content:Source Acronym="ABC" OrganizationName="ABC" />
</DItem>
</Item>
</Items>
</content>
</entry>
</root>
var xmldoc = new XmlDocument();
var xmlns = new XmlNamespaceManager(xmldoc.NameTable);
xmlns.AddNamespace("DItems", "http://www.namespace.xsd");
xmldoc.Load(url);
var titleNodes = xmldoc.SelectNodes("//DItems:DItem/#Title", xmlns);
var result = titleNodes.Cast<XmlAttribute>().Select(a => a.Value).ToList();
Output (list of objects):
my title1
my title2
my title3

SharePoint GetListItems - Get all columns, filter by set List ID . C#

In this WS conumer C# code - , what's the simplest way to Get back all list columns (I only see 10 attributes avaliable) and to filter a a set ID=3. Do I have to qualify all of them in the ndViewFields? where do I place my caml Where? Thanks.
XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
ndQueryOptions.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>FALSE</DateInUtc><ExpandUserField>FALSE</ExpandUserField>";
//ndViewFields.InnerXml = "<FieldRef Name='Title' /><FieldRef Name='Title' />"; //you don't need to specifically request the 'ID' column since it will be returned regardless
ndViewFields.InnerXml = "<FieldRef Name='Title' />"; //you don't need to specifically request the 'ID' column since it will be returned regardless
ndQuery.InnerXml = "<OrderBy><FieldRef Name='Title'/></OrderBy>";
try
{
XmlNode ndListItems = wList.GetListItems("MyList", string.Empty, ndQuery, ndViewFields,null, ndQueryOptions, null);
foreach (XmlNode node in ndListItems)
{
if (node.Name == "rs:data")
{
for (int f = 0; f < node.ChildNodes.Count; f++)
{
if (node.ChildNodes[f].Name == "z:row")
{
//Add the employee ID to my 'employeeIDs' ArrayList
Titles.Add(node.ChildNodes[f].Attributes["ows_Title"].Value);
Your ndQuery should contain:
<Query>
<Where>
<Eq>
<FieldRef Name="ID" />
<Value Type="Counter">3</Value>
</Eq>
</Where>
</Query>
and ndViewFields should contain:
<ViewFields>
<FieldRef Name="ID" />
<FieldRef Name="Title" />
... all other fields you need
</ViewFields>
Whole XML should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>GUID Or Name</listName>
<query>
<Query xmlns="">
<Where>
<Eq>
<FieldRef Name="ID" />
<Value Type="Counter">1</Value>
</Eq>
</Where>
</Query>
</query>
<viewFields>
<ViewFields xmlns="">
<FieldRef Name="ID" />
<FieldRef Name="Title" />
</ViewFields>
</viewFields>
<queryOptions>
<QueryOptions xmlns="" />
</queryOptions>
</GetListItems>
</soap:Body>
</soap:Envelope>

Categories