LINQ query for XML c# - c#

I have simple loop for finding child Element:
XDocument xDoc = XDocument.Load(#"bpmn.xml");
//Run query
foreach (XElement level1Element in xelement.Elements("process"))
{
System.Diagnostics.Debug.WriteLine(level1Element.Attribute("id").Value);
foreach (XElement level2Element in level1Element.Elements("task"))
{
System.Diagnostics.Debug.WriteLine(
" " + level2Element.Attribute("name").Value);
}
}
Why don't I get any output?
The input XML:
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:tns="http://sourceforge.net/bpmn/definitions/_1384266732154" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:yaoqiang="http://bpmn.sourceforge.net" exporter="Yaoqiang BPMN Editor" exporterVersion="2.2.18 (GPLv3, Non-Commercial)" expressionLanguage="http://www.w3.org/1999/XPath" id="_1384266732154" name="" targetNamespace="http://sourceforge.net/bpmn/definitions/_1384266732154" typeLanguage="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL http://bpmn.sourceforge.net/schemas/BPMN20.xsd"> <collaboration id="COLLABORATION_1" isClosed="false">
<participant id="_2" name="CEO" processRef="PROCESS_1">
<participantMultiplicity maximum="1" minimum="0"/>
</participant>
<participant id="_3" name="Manager" processRef="PROCESS_2">
<participantMultiplicity maximum="1" minimum="0"/>
</participant>
<participant id="_4" name="project Manager" processRef="PROCESS_3">
<participantMultiplicity maximum="1" minimum="0"/>
</participant>
<participant id="_5" name="HR" processRef="PROCESS_4">
<participantMultiplicity maximum="1" minimum="0"/>
</participant>
<participant id="_6" name="Employee" processRef="PROCESS_5">
<participantMultiplicity maximum="1" minimum="0"/>
</participant> </collaboration> <process id="PROCESS_1" isClosed="false" isExecutable="true" processType="None">
<startEvent id="_8" isInterrupting="true" name="Start Event" parallelMultiple="false">
<outgoing>_12</outgoing>
</startEvent>
<task completionQuantity="1" id="_9" isForCompensation="false" name="Task" startQuantity="1">
<incoming>_12</incoming>
<outgoing>_13</outgoing>
</task>
<sendTask completionQuantity="1" id="_10" implementation="##WebService" isForCompensation="false" name="Send Task" startQuantity="1">
<incoming>_13</incoming>
<outgoing>_14</outgoing>
</sendTask>
<task completionQuantity="1" id="_11" isForCompensation="false" name="Task" startQuantity="1">
<incoming>_14</incoming>
</task>
<sequenceFlow id="_12" sourceRef="_8" targetRef="_9"/>
<sequenceFlow id="_13" sourceRef="_9" targetRef="_10"/>
<sequenceFlow id="_14" sourceRef="_10" targetRef="_11"/> </process> <process id="PROCESS_2" isClosed="false" isExecutable="true" processType="None">
<task completionQuantity="1" id="_17" isForCompensation="false" name="Task" startQuantity="1">
<outgoing>_21</outgoing>
</task>
<task completionQuantity="1" id="_19" isForCompensation="false" name="Task" startQuantity="1">
<incoming>_21</incoming>
<outgoing>_23</outgoing>
<outgoing>_25</outgoing>
</task>
<sequenceFlow id="_21" sourceRef="_17" targetRef="_19"/>
<receiveTask completionQuantity="1" id="_22" implementation="##WebService" instantiate="false" isForCompensation="false" name="Receive Task" startQuantity="1">
<incoming>_23</incoming>
</receiveTask>
<sequenceFlow id="_23" name="go on" sourceRef="_19" targetRef="_22"/>
<task completionQuantity="1" id="_24" isForCompensation="false" name="Task" startQuantity="1">
<incoming>_25</incoming>
</task>
<sequenceFlow id="_25" sourceRef="_19" targetRef="_24"/> </process> </definitions>

You need to get the root element first, by xDoc.Root (if xelement in your code is xDoc)
(The main problem here) Your XML has a custom namespace, in which case you need to specify it when calling Elements().
Putting together:
XDocument xDoc = XDocument.Load(#"bpmn.xml");
var ns = XNamespace.Get("http://www.omg.org/spec/BPMN/20100524/MODEL");
//Run query
foreach(XElement level1Element in xDoc.Root.Elements(ns + "process"))
{
System.Diagnostics.Debug.WriteLine(level1Element.Attribute("id").Value);
foreach(XElement level2Element in level1Element.Elements(ns + "task"))
{
System.Diagnostics.Debug.WriteLine(" " + level2Element.Attribute("name").Value);
}
}

You need to select from the root element. Try changing:
xelement.Elements("process"))
To:
xDoc.Elements("definitions").Elements("process")

Your .xml file provided with namespace, still you should use it in your code. Please try this:
XDocument xDoc = XDocument.Load(#"xmlfile1.xml");
//Run query
XNamespace ns = "http://www.omg.org/spec/BPMN/20100524/MODEL";
foreach (XElement level1Element in xDoc.Descendants(ns + "process"))
{
System.Diagnostics.Debug.WriteLine(level1Element.Attribute("id").Value);
foreach (XElement level2Element in level1Element.Elements(ns + "task"))
{
System.Diagnostics.Debug.WriteLine(
" " + level2Element.Attribute("name").Value);
}
}
Also, in your case use Descendants() method instead of Elements().
More info http://msdn.microsoft.com/en-us/library/system.xml.linq.xname(v=vs.110).aspx

Related

How I can fill my ASP.NET TreeView out of Code?

hi guys i have a problem with the treeview control in asp.net. I want to fill that with a xml file but the treeview in asp.net is diffrent to the window form treeview control :/
The name of my treeview is treeview...i don't have the xml in a folder I create a xml string and use this but in this example i only want test how i can fill this treeview out of code. how i can do this with my method?
here is my code:
XElement doc = XElement.Load("~/App_Data/test_xml.xml");
TreeNode Feature;
TreeNode User;
foreach (XElement state in doc.Descendants("FEATURE"))
{
Feature = treeview.Nodes.Add(state.Attribute("NAME").Value);
foreach (XElement region in state.Descendants("USER"))
{
User =
Feature.Nodes.Add(region.Attribute("NAME").Value);
foreach (XElement area in region.Descendants("NAME"))
{
User.Nodes.Add(area.Attribute("NAME").Value);
}
}
}
my xml example:
<?xml version="1.0" encoding="UTF-8"?>
<LM-X STAT_VERSION="3.32">
<LICENSE_PATH TYPE="NETWORK" HOST="Server002" SERVER_VERSION="4.4.4" UPTIME="53 day(s) 21 hour(s) 10 min(s) 50 sec(s)">
<FEATURE NAME="GlobalZoneEU" VERSION="12.0" VENDOR="ALTAIR" START="2013-03-26" END="2014-03-31" USED_LICENSES="111720" TOTAL_LICENSES="147000" SHARE="CUSTOM ,VIRTUAL">
<USER NAME="SYSTEM" HOST="Server1" IP="" USED_LICENSES="2000" LOGIN_TIME="2013-04-17 12:42" CHECKOUT_TIME="2013-04-17 12:42" SHARE_CUSTOM=""/>
>
<USER NAME="Admin" HOST="Server1" IP="" USED_LICENSES="720" LOGIN_TIME="2013-04-17 12:44" CHECKOUT_TIME="2013-04-17 12:44" SHARE_CUSTOM=""/>
>
<USER NAME="Test.A" HOST="4327" IP="" USED_LICENSES="21000" LOGIN_TIME="2013-05-21 07:52" CHECKOUT_TIME="2013-05-21 07:52" SHARE_CUSTOM=""/>
>
<USER NAME="Test.B" HOST="4327" IP="" USED_LICENSES="6000" LOGIN_TIME="2013-05-21 07:54" CHECKOUT_TIME="2013-05-21 07:54" SHARE_CUSTOM=""/>
>
<USER NAME="Test.C" HOST="4970" IP="" USED_LICENSES="21000" LOGIN_TIME="2013-05-21 08:15" CHECKOUT_TIME="2013-05-21 08:15" SHARE_CUSTOM=""/>
</FEATURE>
<FEATURE NAME="HWAIFPBS" VERSION="12.0" VENDOR="ALTAIR" START="2013-03-26" END="2014-03-31" USED_LICENSES="0" TOTAL_LICENSES="2147483647" SHARE="CUSTOM ,VIRTUAL"/>
<FEATURE NAME="HWAWPF" VERSION="12.0" VENDOR="ALTAIR" START="2013-03-26" END="2014-03-31" USED_LICENSES="0" TOTAL_LICENSES="2147483647" SHARE="CUSTOM ,VIRTUAL"/>
<FEATURE NAME="HWAcuconsole" VERSION="12.0" VENDOR="ALTAIR" START="2013-03-26" END="2014-03-31" USED_LICENSES="0" TOTAL_LICENSES="2147483647" SHARE="CUSTOM ,VIRTUAL"/>
</LICENSE_PATH>
</LM-X>
You can use XmlDataSource as Jeremy suggested or change code as below
XElement doc = XElement.Load("~/App_Data/test_xml.xml");
TreeNode root = new TreeNode("FEATURES");
foreach (XElement state in doc.Descendants("FEATURE"))
{
TreeNode feature = new TreeNode(state.Attribute("NAME").Value);
foreach (XElement region in state.Descendants("USER"))
{
TreeNode user = new TreeNode(region.Attribute("NAME").Value);
foreach (XElement area in region.Descendants("NAME"))
{
user.ChildNodes.Add(new TreeNode(area.Attribute("NAME").Value));
}
feature.ChildNodes.Add(user);
}
root.ChildNodes.Add(feature);
}
treeview.Nodes.Add(root);

Not able to get the element with XDocument

Below is the code i am using to get the value of the 'name'(attribute) of the 'person'
parameter tag="person" and parameter attribute="name"
public static string GetInformationFromXML(string tag,
string attribute,
string filePath)
{
XDocument doc = XDocument.Load(filePath);
string info = doc.Element(tag).Attribute(attribute).Value;
return info;
}
doc.Element(tag) is not getting the element even though when i expand doc, it does have an element with type 'Element' and Name 'person'
the file being read is XmlDocument for your information.
below is the xml of the file i am trying to read
<?xml version="1.0"?>
<import>
<company name1="ABC" name2="" action="create"
profile="\Profiles\ABC\" id="C1">
<address street="industrial" city="london"
country="england" id="A1">
<telecom type="phone" value="4839282992"
desc="" default="true" />
<telecom type="fax" value="3232" desc="" />
</address>
</company>
<person title="Mr." name="Tariq" surname="sheikh"
lang="EN" action="create" profile="Profiles\Tariq"
login="tariq" password="123456" default_address="A1">
<link reference="C1" type="Employee" description="Software developer" />
<address street="baker street" zip="12443"
city="london" country="england" />
<account bank="Barclays" account="4378734834" />
<telecom type="email" value="tariq.sheikh#abc.co.in" desc="" />
<registration type="temporaryID"
value="4623648c-739e-49c8-93fa-41dc7fed53ea" />
</person>
</import>
I am new to XDocument !
You have to use Descendants when element you're looking for is not direct child of current element (or root for XDocument).
string info = doc.Descendants(tag).First().Attribute(attribute).Value;

Linq to XML C# Descendants: How to read Attributes with the same name?

I search the Web and found many answers, but they all worked with a specific class or written in another way.
I have this XML-Response:
<return xsi:type="ns1:PlentySoapResponse_GetItemsBase">
<ItemsBase xsi:type="ns1:ArrayOfPlentysoapobject_itembase">
<item xsi:type="ns1:PlentySoapObject_ItemBase">
<ItemID xsi:type="xsd:int">2</ItemID>
<ItemNo xsi:type="xsd:string"/>
.............
<DeepLink xsi:type="xsd:string">/a-2/</DeepLink>
</item>
<item xsi:type="ns1:PlentySoapObject_ItemBase">
<ItemID xsi:type="xsd:int">4</ItemID>
<ItemNo xsi:type="xsd:string"/>
And i read it this way:
XDocument loaded = XDocument.Parse(readString);
for (int i = 0; i < 50; i++)
{
var items = from x in loaded.Descendants("return")
select new
{
ItemID = x.Descendants("ItemID").First().Value,
Name = x.Descendants("Name").First().Value,
EKnet = x.Descendants("PurchasePriceNet").First().Value
};
foreach (var x in items)
{
item[i, 0] = x.ItemID.ToString();
item[i, 1] = x.Name.ToString();
item[i, 2] = x.EKnet.ToString();
}
}
else
{
MessageBox.Show("Wrong XML Call");
}
return item;
}
But I always get the same item Attributes.
Is there an easy way to get the next Item Attributes?
I read an exmaple with "IEnumerable" but this always uses a specific class, wich I dont want to use.
Many thanks in advance.
Edit:
<SOAP-ENV:Body>
<ns1:GetItemsBaseResponse>
<return xsi:type="ns1:PlentySoapResponse_GetItemsBase">
<ItemsBase xsi:type="ns1:ArrayOfPlentysoapobject_itembase">
<item xsi:type="ns1:PlentySoapObject_ItemBase">
<ItemID xsi:type="xsd:int">2</ItemID>
<ItemNo xsi:type="xsd:string"/>
<ExternalItemID xsi:type="xsd:string"/>
<EAN1 xsi:type="xsd:string">0023272005641</EAN1>
<EAN2 xsi:type="xsd:string"/>
<EAN3 xsi:type="xsd:string"/>
<EAN4 xsi:type="xsd:string"/>
<ISBN xsi:type="xsd:string"/>
<ASIN xsi:type="xsd:string">B000NTAG66</ASIN>
<Type xsi:type="xsd:int">0</Type>
<Model xsi:type="xsd:string"/>
<ProducerID xsi:type="xsd:int">0</ProducerID>
<VATInternalID xsi:type="xsd:int">0</VATInternalID>
<Marking1ID xsi:type="xsd:int">0</Marking1ID>
<Marking2ID xsi:type="xsd:int">11</Marking2ID>
<CustomsTariffNumber xsi:type="xsd:string"/>
<FSK xsi:type="xsd:int">0</FSK>
<Condition xsi:type="xsd:int">0</Condition>
<Position xsi:type="xsd:string"/>
<StorageLocation xsi:type="xsd:int">0</StorageLocation>
<WebShopSpecial xsi:type="xsd:string">0</WebShopSpecial>
<Published xsi:type="xsd:int">0</Published>
<LastUpdate xsi:type="xsd:int">1344392167</LastUpdate>
<ItemURL xsi:nil="true"/>
<EbayEPID xsi:type="xsd:string"/>
<ParcelServicePresetIDs xsi:type="ns1:ArrayOfPlentysoapobject_integer">
<item xsi:type="ns1:PlentySoapObject_Integer">
<intValue xsi:type="xsd:int">21</intValue>
</item>
</ParcelServicePresetIDs>
<ProducingCountryID xsi:type="xsd:int">1</ProducingCountryID>
<FreeTextFields xsi:type="ns1:PlentySoapObject_ItemFreeTextFields">
<Free1 xsi:type="xsd:string"/>
<Free2 xsi:type="xsd:string"><![CDATA[http://games.shop.ebay.de/PC-Videospiele-/1249/i.html?LH_BIN=1&LH_ItemCondition=11&Plattform=Xbox%2520360&_trkparms=65%253A12%257C66%253A2%257C39%253A1%257C72%253A4674&rt=nc&_nkw=star+wars+force+unleashed&_catref=1&_dmpt=de_entertainment_games&_trksid=p3286.c0.m14&_sop=15&_sc=1]]></Free2>
<Free3 xsi:type="xsd:string"/>
<Free4 xsi:type="xsd:string">1</Free4>
<Free5 xsi:type="xsd:string">UK-Import: Spiel in Deutsch, Anleitung in Englisch</Free5>
<Free6 xsi:type="xsd:string">Actionspiele</Free6>
<Free7 xsi:type="xsd:string">XBOX 360</Free7>
<Free8 xsi:type="xsd:string">ages_12_and_over</Free8>
<Free9 xsi:type="xsd:string"/>
<Free10 xsi:type="xsd:string">1</Free10>
<Free11 xsi:type="xsd:string">0</Free11>
<Free12 xsi:nil="true"/>
<Free13 xsi:nil="true"/>
<Free14 xsi:nil="true"/>
<Free15 xsi:nil="true"/>
<Free16 xsi:nil="true"/>
<Free17 xsi:nil="true"/>
<Free18 xsi:nil="true"/>
<Free19 xsi:nil="true"/>
<Free20 xsi:nil="true"/>
</FreeTextFields>
<Texts xsi:type="ns1:PlentySoapObject_ItemTexts">
<Lang xsi:type="xsd:string">de</Lang>
<Name xsi:type="xsd:string">Star Wars: The Force Unleashed 1 - Xbox 360</Name>
<Name2 xsi:type="xsd:string"/>
<Name3 xsi:type="xsd:string"/>
<ShortDescription xsi:nil="true"/>
<LongDescription xsi:nil="true"/>
<TechnicalData xsi:nil="true"/>
<MetaDescription xsi:nil="true"/>
<Keywords xsi:type="xsd:string"/>
</Texts>
<PriceSet xsi:type="ns1:PlentySoapObject_ItemPriceSet">
<PriceID xsi:type="xsd:int">2</PriceID>
<Lot xsi:type="xsd:float">0</Lot>
<Unit xsi:type="xsd:string">C62</Unit>
<Unit1 xsi:type="xsd:string"/>
<Unit2 xsi:type="xsd:string"/>
<PackagingUnit xsi:type="xsd:string">1</PackagingUnit>
<Price xsi:type="xsd:float">20.99</Price>
<Price1 xsi:type="xsd:float">18.65</Price1>
<Price2 xsi:type="xsd:float">23.99</Price2>
<Price3 xsi:type="xsd:float">999</Price3>
<Price4 xsi:type="xsd:float">999</Price4>
<Price5 xsi:type="xsd:float">0</Price5>
<Price6 xsi:type="xsd:float">0</Price6>
<Price7 xsi:type="xsd:float">0</Price7>
<Price8 xsi:type="xsd:float">0</Price8>
<Price9 xsi:type="xsd:float">0</Price9>
<Price10 xsi:type="xsd:float">0</Price10>
<Price11 xsi:type="xsd:float">23.7</Price11>
<Price12 xsi:type="xsd:float">33.7</Price12>
<RRP xsi:type="xsd:float">0</RRP>
<VAT xsi:type="xsd:float">19</VAT>
<WeightInGramm xsi:type="xsd:int">0</WeightInGramm>
<WidthInMM xsi:type="xsd:int">0</WidthInMM>
<LengthInMM xsi:type="xsd:int">0</LengthInMM>
<HeightInMM xsi:type="xsd:int">0</HeightInMM>
<Position xsi:type="xsd:int">0</Position>
<ShowOnly xsi:type="xsd:int">0</ShowOnly>
<RebateLevelPrice6 xsi:type="xsd:int">0</RebateLevelPrice6>
<RebateLevelPrice7 xsi:type="xsd:int">0</RebateLevelPrice7>
<RebateLevelPrice8 xsi:type="xsd:int">0</RebateLevelPrice8>
<PurchasePriceNet xsi:type="xsd:float">14.38</PurchasePriceNet>
<Package xsi:type="xsd:int">0</Package>
<TypeOfPackage xsi:type="xsd:int">0</TypeOfPackage>
<UnitLoadDevice xsi:type="xsd:int">0</UnitLoadDevice>
</PriceSet>
<Stock xsi:type="ns1:PlentySoapObject_ItemStock">
<Limitation xsi:type="xsd:int">1</Limitation>
<MainWarehouseID xsi:type="xsd:int">2</MainWarehouseID>
<WebshopVisiblePositiveStock xsi:type="xsd:boolean">false</WebshopVisiblePositiveStock>
<WebshopInvisibleNoStock xsi:type="xsd:boolean">false</WebshopInvisibleNoStock>
<ChangeAvailablePositiveStock xsi:type="xsd:boolean">true</ChangeAvailablePositiveStock>
<ChangeNotAvailableNoStock xsi:type="xsd:boolean">true</ChangeNotAvailableNoStock>
<ChangeAvailablePositiveStockVariant xsi:type="xsd:boolean">false</ChangeAvailablePositiveStockVariant>
<ChangeNotAvailableNoStockVariant xsi:type="xsd:boolean">false</ChangeNotAvailableNoStockVariant>
<StorageLocation xsi:nil="true"/>
</Stock>
<Availability xsi:type="ns1:PlentySoapObject_ItemAvailability">
<AvailabilityID xsi:type="xsd:int">5</AvailabilityID>
<Webshop xsi:type="xsd:int">1</Webshop>
<WebAPI xsi:type="xsd:int">1</WebAPI>
<Inactive xsi:type="xsd:int">0</Inactive>
<AmazonFBA xsi:type="xsd:int">1</AmazonFBA>
<AmazonFEDAS xsi:type="xsd:string"/>
<AmazonProduct xsi:type="xsd:int">31</AmazonProduct>
<Gimahhot xsi:type="xsd:int">0</Gimahhot>
<GoogleBase xsi:type="xsd:int">0</GoogleBase>
<Hitmeister xsi:type="xsd:int">0</Hitmeister>
<MeinPaket xsi:type="xsd:int">0</MeinPaket>
<Mercateo xsi:type="xsd:int">0</Mercateo>
<Quelle xsi:type="xsd:int">0</Quelle>
<Moebelprofi xsi:type="xsd:int">0</Moebelprofi>
<Zalando xsi:type="xsd:int">0</Zalando>
<Restposten xsi:type="xsd:int">0</Restposten>
<Shopgate xsi:type="xsd:int">0</Shopgate>
<Shopperella xsi:type="xsd:int">0</Shopperella>
<ShopShare xsi:type="xsd:int">0</ShopShare>
<Tradoria xsi:type="xsd:int">0</Tradoria>
<TradoriaCategory xsi:type="xsd:int">0</TradoriaCategory>
<Yatego xsi:type="xsd:int">0</Yatego>
<AvailableUntil xsi:type="xsd:int">0</AvailableUntil>
<MaximumSalesOrderQuantity xsi:type="xsd:int">0</MaximumSalesOrderQuantity>
<Neckermann xsi:type="xsd:int">0</Neckermann>
</Availability>
<Others xsi:nil="true"/>
<Categories xsi:nil="true"/>
<AttributeValueSets xsi:nil="true"/>
<ItemSuppliers xsi:nil="true"/>
<ItemProperties xsi:nil="true"/>
<ItemAttributeMarkup xsi:nil="true"/>
<BundleType xsi:nil="true"/>
<DeepLink xsi:type="xsd:string">/a-2/</DeepLink>
</item>
Try this:
XDocument loaded = XDocument.Parse(readString);
var items = loaded
.Descendants("return")
.FirstOrDefault()
.Element("ItemsBase")
.Elements("item");
int i = 0;
foreach (var _item in items)
{
item[i, 0] = _item.Element("ItemID").Value;
item[i, 1] = _item.Element("Texts").Element("Name").Value;
item[i, 2] = _item.Element("PriceSet").Element("PurchasePriceNet").Value;
i++;
}
XDocument xdoc = XDocument.Parse(xml);
var items = from ret in xdoc.Descendants("return")
from itb in ret.Descendants("ItemsBase")
from item in itb.Descendants("item")
select new {item};
foreach (var item in items)
{
// do what you want with item,
}

reading an xmlnode using xmlDocment

how can i read an Id from the below sample XML >>> CatalogItem Id="3212" and OrganizationName
string xmlfile = #"C:\Users\easwaranp\Desktop\test.xml";
ArrayList arrResult = new ArrayList();
string sContent = File.ReadAllText(xmlfile);
StringReader DocumentReader = new StringReader(sContent);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(DocumentReader);
XmlNodeList ReferenceNodes = xmlDoc.GetElementsByTagName("content:Topic");
foreach (XmlNode Node in ReferenceNodes)
{
string sTopicName = Node.ParentNode.ParentNode.Attributes["OrganizationName"].Value;
}
foreach (string s in arrResult)
{
Console.WriteLine(s);
}
Console.Read();
<content type="application/xml">
<CatalogItems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="sitename.xsd">
<CatalogSource Acronym="ABC" OrganizationName="ABC Corporation" />
<CatalogItem Id="32122" CatalogUrl="urlname">
<ContentItem xmlns:content="sitename.xsd" Title="Department 1">
<content:SelectionSpec ClassList="" ElementList="" />
<content:Language Value="eng" Scheme="ISO 639-2" />
<content:Source Acronym="ABC" OrganizationName="ABC Corporation1" />
<content:Topics Scheme="ABC">
<content:Topic TopicId="1" TopicName="Marketing1" />
<content:Topic TopicId="11" TopicName="Coverage1" />
</content:Topics>
</ContentItem>
</CatalogItem>
<CatalogItem Id="3212" CatalogUrl="urlname">
<ContentItem xmlns:content="sitename.xsd" Title="Department 2">
<content:SelectionSpec ClassList="" ElementList="" />
<content:Language Value="eng" Scheme="ISO 639-2" />
<content:Source Acronym="ABC" OrganizationName="ABC Corporation2" />
<content:Topics Scheme="ABC">
<content:Topic TopicId="2" TopicName="Marketing2" />
<content:Topic TopicId="22" TopicName="Coverage2" />
</content:Topics>
</ContentItem>
</CatalogItem>
<CatalogItem Id="32132" CatalogUrl="urlname">
<ContentItem xmlns:content="sitename.xsd" Title="Department 3">
<content:SelectionSpec ClassList="" ElementList="" />
<content:Language Value="eng" Scheme="ISO 639-2" />
<content:Source Acronym="ABC" OrganizationName="ABC Corporation3" />
<content:Topics Scheme="ABC">
<content:Topic TopicId="3" TopicName="Marketing3" />
<content:Topic TopicId="33" TopicName="Coverage3" />
</content:Topics>
</ContentItem>
</CatalogItem>
</CatalogItems>
</content>
using System;
using System.IO;
using System.Xml;
class GetValue{
public static void Main(){
var xmlDoc = new XmlDocument();
xmlDoc.Load("test.xml");
var xmlRoot = xmlDoc.DocumentElement;
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("content", "sitename.xsd");
var attr = xmlRoot.SelectSingleNode("descendant::content:Source/#OrganizationName[../../../#Id='3212']", nsmgr);
if(attr == null)
Console.WriteLine("not found!");
else
Console.WriteLine(attr.Value);
}
}
OUTPUT:
ABC Corporation2
XPath is your friend when it comes to tasks like this. I adapted the following code from a tutorial on codeproject.com. I don't know if it works (or will even compile), but it should get you started in the right direction. Also, I'm assuming your talking about C#, but in case I've misunderstood what language you're using, please disregard (a language tag on your question might help).
using System.Xml;
using System.Xml.XPath;
....
string fileName = "test.xml";
XPathDocument doc = new XPathDocument(fileName);
XPathNavigator nav = doc.CreateNavigator();
// Compile a standard XPath expression
XPathExpression expr;
idExpr = nav.Compile("/content/CatalogItems/CatalogItem/#id");
XPathNodeIterator iterator = nav.Select(idExpr);
// Iterate on the node set
try
{
while (iterator.MoveNext())
{
XPathNavigator nav2 = iterator.Current.Clone();
Console.WriteLine("id: " + nav2.Value);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}

create a xml file with namespace

<?xml version="1.0" encoding="UTF-8"?>
<manifest identifier="D2L_1000000179" xmlns:d2l_2p0="http://desire2learn.com/xsd/d2lcp_v2p0" xmlns="http://www.imsglobal.org/xsd/imscp_v1p1">
<resources>
<resource identifier="res_question_library" type="webcontent" d2l_2p0:material_type="d2lquestionlibrary" d2l_2p0:link_target="" href="questiondb.xml" title="Question Library" />
<resource identifier="res_quiz_1000000179" type="webcontent" d2l_2p0:material_type="d2lquiz" d2l_2p0:link_target="" href="quiz_d2l_1000000179.xml" title="Quiz to test D2L import" />
</resources>
</manifest>
I want to create this xml file .
but when i am creating this using Xelement or XmlElemenmt i am getting this one
<?xml version="1.0" encoding="UTF-8"?>
<manifest identifier="D2L_1000000179" xmlns:d2l_2p0="http://desire2learn.com/xsd/d2lcp_v2p0" xmlns="http://www.imsglobal.org/xsd/imscp_v1p1">
<resources>
<resource identifier="res_question_library" type="webcontent" material_type="d2lquestionlibrary" link_target="" href="questiondb.xml" title="Question Library" />
<resource identifier="res_quiz_1000000179" type="webcontent" material_type="d2lquiz" link_target="" href="quiz_d2l_1000000179.xml" title="Quiz to test D2L import" />
</resources>
</manifest>
here d2l_2p0:material_type is coming like material_type.
some one help me to create this using .net framework.
code for this is here below
private void createMenifetData(string destPath, long listExam)
{
XmlDocument xDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xDoc.CreateXmlDeclaration("1.0", "UTF-8", "");
XmlElement rootnode = xDoc.CreateElement("manifest");
xDoc.InsertBefore(xmlDeclaration, xDoc.DocumentElement);
rootnode.SetAttribute("identifier", "D2L_" + listExam.ToString());
rootnode.SetAttribute("xmlns:d2l_2p0", "http://desire2learn.com/xsd/d2lcp_v2p0");
rootnode.SetAttribute("xmlns", "http://www.imsglobal.org/xsd/imscp_v1p1");
XmlElement resources = xDoc.CreateElement("resources");
XmlElement resource = xDoc.CreateElement("resource");
resource.SetAttribute("identifier", "res_question_library");
resource.SetAttribute("type", "webcontent");
resource.SetAttribute(#"d2l_2p0:material_type", "d2lquestionlibrary");
resource.SetAttribute(#"d2l_2p0:link_target", "");
resource.SetAttribute("href", "questiondb.xml");
resource.SetAttribute("title", "Question Library");
resources.AppendChild(resource);
XmlElement resource1 = xDoc.CreateElement("resource");
resource1.SetAttribute("identifier", "res_quiz_" + listExam);
resource1.SetAttribute("type", "webcontent");
resource1.SetAttribute(#"d2l_2p0:material_type", "d2lquiz");
resource1.SetAttribute(#"d2l_2p0:link_target", "");
resource1.SetAttribute("href", "quiz_d2l_" + listExam + ".xml");
resource1.SetAttribute("title", "Quiz to test D2L import");
resources.AppendChild(resource1);
rootnode.AppendChild(resources);
xDoc.AppendChild(rootnode);
xDoc.Save(destPath + "\\imsmanifest.xml");}
XNamespace defaultNamespace = "http://www.imsglobal.org/xsd/imscp_v1p1";
const string NAMESPACE_URI = "http://desire2learn.com/xsd/d2lcp_v2p0";
const string NAMESPACE_PREFIX = "d2l_2p0";
XNamespace otherNamespace = NAMESPACE_URI;
XElement root = new XElement(defaultNamespace + "manifest",
new XAttribute("identifier", "D2L_1000000179"),
new XAttribute(XNamespace.Xmlns + NAMESPACE_PREFIX, NAMESPACE_URI),
new XElement(defaultNamespace + "resources",
new XElement(defaultNamespace + "resource",
new XAttribute("identifier", "res_question_library"),
new XAttribute("type", "webcontent"),
new XAttribute(otherNamespace + "material_type", "d2lquestionlibrary"),
new XAttribute(otherNamespace + "link_target", ""),
new XAttribute("href", "questiondb.xml"),
new XAttribute("title", "Question Library")),
new XElement(defaultNamespace + "resource",
new XAttribute("identifier", "res_quiz_1000000179"),
new XAttribute("type", "webcontent"),
new XAttribute(otherNamespace + "material_type", "d2lquiz"),
new XAttribute(otherNamespace + "link_target", ""),
new XAttribute("href", "quiz_d2l_1000000179.xml"),
new XAttribute("title", "Quiz to test D2L import"))));
Since you tagged this VB I'd just go the simplest route and use XML literals:
Dim T = <manifest identifier="D2L_1000000179" xmlns:d2l_2p0="http://desire2learn.com/xsd/d2lcp_v2p0" xmlns="http://www.imsglobal.org/xsd/imscp_v1p1">
<resources>
<resource identifier="res_question_library" type="webcontent" d2l_2p0:material_type="d2lquestionlibrary" d2l_2p0:link_target="" href="questiondb.xml" title="Question Library"/>
<resource identifier="res_quiz_1000000179" type="webcontent" d2l_2p0:material_type="d2lquiz" d2l_2p0:link_target="" href="quiz_d2l_1000000179.xml" title="Quiz to test D2L import"/>
</resources>
</manifest>
This kicks out:
<manifest identifier="D2L_1000000179" xmlns:d2l_2p0="http://desire2learn.com/xsd/d2lcp_v2p0" xmlns="http://www.imsglobal.org/xsd/imscp_v1p1">
<resources>
<resource identifier="res_question_library" type="webcontent" d2l_2p0:material_type="d2lquestionlibrary" d2l_2p0:link_target="" href="questiondb.xml" title="Question Library" />
<resource identifier="res_quiz_1000000179" type="webcontent" d2l_2p0:material_type="d2lquiz" d2l_2p0:link_target="" href="quiz_d2l_1000000179.xml" title="Quiz to test D2L import" />
</resources>
</manifest>
Use CreateAttribute method on XMLDocument to create an attribute with a namespace. Later append to the attributes collection of xmlelement that should have this attribute.
public XmlAttribute CreateAttribute(
string qualifiedName,
string namespaceURI
)

Categories