How to change an attribute in a subnode in C#? - c#

I want to change the attribute value (in this case "51") of the "NextMemberId" in an xml file that looks like this:
<File>
<MemberList>
<NextMemberId Value="51" />
<Member Id="1" ..... />
<Member Id="2" ..... />
</MemberList>
</File>
The following code works, but I would like to know if it can be done in a more direct way without having to run a foreach loop:
var memberId = 1;
var memberlist = Doc.DocumentElement.SelectSingleNode("MemberList");
foreach (XmlNode node in memberlist.ChildNodes)
{
var nodeElement = node as XmlElement;
if (nodeElement != null && nodeElement.Name == "NextMemberId")
{
nodeElement.SetAttribute("Value", memberId.ToString());
}
}
Thanks for any inspiration!

The correct path to get NextMemberId from File according to your sample XML would be :
var nodeElement = Doc.DocumentElement.SelectSingleNode("MemberList/NextMemberId");
nodeElement.SetAttribute("Value", memberId.ToString());
If there are multiple NextMemberId in your actual XML, and you need to filter by Value attribute, then you can add an XPath predicate similar to what the other answer suggested :
var nodeElement = Doc.DocumentElement.SelectSingleNode("MemberList/NextMemberId[#Value=51");
Notice that you can choose to keep or leave single-quotes around 51 depending on whether you want compare the Value as a string or a number, respectively.

You can select single node with specified attribute like this:
var nextMemberIdNode = Doc.DocumentElement.SelectSingleNode("NextMemberId[#Value='51']")

Related

Remove Child Nodes Keep Their Parent

I have XML Code Block as below (it is part of similar lines of hundreds..):
<specs>
<spec name='fald' value = '100'>
<name></name>
<value></value>
</spec>
</specs>
I need to convert code as seen below:
<specs>
<spec name ='fald' value = '100'/>
</specs>
Using following code I am able to delete child nodes:
foreach (XElement child in doc.Descendants().Reverse())
{
if (child.HasAttributes)
{
foreach (var attribute in child.Attributes())
{
if (string.IsNullOrEmpty(attribute.Value) && string.IsNullOrEmpty(child.Value))
child.Remove();
}
}
}
But this process also deletes parent node ('spec') which is expected to take place there. Any help is appreciated, thanks...
It's a little unclear what the criteria for deleting an element is, but to get you started, perhaps this is somewhere along the lines of what you are looking for?
var xml =
#"<specs>
<spec name='fald' value='100'>
<name></name>
<value></value>
</spec>
</specs>";
var doc = XElement.Parse(xml);
var childrenToDelete = doc.XPathSelectElements("//spec/*")
.Where(elem => string.IsNullOrEmpty(elem.Value)
&& (!elem.HasAttributes
|| elem.Attributes().All(attr => string.IsNullOrEmpty(attr.Value))))
.ToList();
foreach (var child in childrenToDelete)
{
child.Remove();
}
// Produces:
// <specs>
// <spec name="fald" value="100" />
// </specs>
Check this fiddle for a test run.

How can i get a collection of child elements - query returns null using Xdocument

Can anybody please tell me why this Xdocument query is returning null when there are elements / attributes that i'm trying to grab.
I'm trying to get a collection of the <version> elements so i can read the attributes of them. Example XML:
<dmodule>
<idstatus>
<dmaddres>
<dmc>Some DMC</dmc>
<dmtitle><techname>My techname</techname><infoname>My infoname</infoname></dmtitle>
<issno issno="004" type="revised">
<issdate year="2016" month="11" day="30"></dmaddres>
<status>
<security class="2">
<rpc>RPC1</rpc>
<orig>ORIG1</orig>
<applic>
<model model="2093">
**<version version="BASE"></version>
<version version="RNWB"></version>**</model></applic>
<techstd>
<autandtp>
<authblk></authblk>
<tpbase>-</tpbase></autandtp>
<authex></authex>
<notes></notes></techstd>
<qa>
<firstver type="tabtop"></qa></status>
</idstatus>
<dmodule>
And this is how i'm trying to get the <version> elements:
XDocument doc = XDocument.Load(sgmlReader);
List<string> applicabilityList = null;
//this doesn't work
//var applics = doc.XPathSelectElements("dmodule/idstatus/status/applic/model/version");
//nor does this
var applics = doc.Descendants("idstatus").Descendants("applic").Elements("version");
foreach (var applic in applics)
{
string applicVersion = applic.Attribute("version").ToString();
applicabilityList.Add(applicVersion);
}
return applicabilityList;
Either query as shown above returns no results. Cleary a silly mistake in my query but i'm out of practice.
That's because you are missing the model element.
...
<applic>
<model model="2093">
<version version="BASE"></
...
If all you are interested are the version elements you can simply do:
var versions = doc.Descendants("version");
This is the working code
var applics = doc.Descendants("dmodule")
.Descendants("idstatus")
.Descendants("status")
.Descendants("security")
.Descendants("applic")
.Descendants("model")
.Elements("version");

C# - Issues Selecting XML with Linq

I am trying to pull an event description in XML, but I am having trouble accessing the data.
I am trying to access the eventDetailsValue element.
Here is a sample of my code:
(version 1)
XElement doc = XElement.Parse(e.Result);
evtDesc = doc.Element("eventDetails").Element("eventDetails").Element("eventDetailsValue").Element("eventDetailsValue").Value;
(version2)
XElement doc = XElement.Parse(e.Result);
var xGood = from detaildoc in doc.Descendants("eventDetails")
from d in detaildoc.Elements("eventDetail").Elements("eventDetailsValue")
select d;
I have tried the following for a different element and it worked:
GeoLat = Convert.ToDouble(doc.Element("latitude").Value);
Here is a sample of the xml result (i removed the values for simplicity):
<event>
<longitude></longitude>
<latitude></latitude>
<category></category>
<dma></dma>
<activeAdvantage></activeAdvantage>
<seoUrl></seoUrl>
<assetID></assetID>
<eventID></eventID>
<eventDetailsPageUrl></eventDetailsPageUrl>
- <mediaTypes>
<mediaType></mediaType>
<mediaType></mediaType>
<mediaType></mediaType>
<mediaType></mediaType>
<mediaType></mediaType>
</mediaTypes>
<eventContactEmail />
<eventContactPhone />
<eventName></eventName>
<eventDate></eventDate>
<eventLocation></eventLocation>
<eventAddress></eventAddress>
<eventCity></eventCity>
<eventState></eventState>
<eventZip></eventZip>
<eventCountry></eventCountry>
<usatSanctioned></usatSanctioned>
<regOnline></regOnline>
<eventCloseDate></eventCloseDate>
<currencyCode></currencyCode>
<eventTypeID></eventTypeID>
<eventType></eventType>
<hasEventResults></hasEventResults>
<hasMetaResults></hasMetaResults>
<showMap></showMap>
<eventContactEmail />
<eventContactPhone />
<displayCloseDate></displayCloseDate>
<excludedFromEmailing></excludedFromEmailing>
<regOpensMessage />
<regFunnel></regFunnel>
<isValid></isValid>
<displayRegistration></displayRegistration>
- <channels>
- <channel>
<channelName></channelName>
<primaryChannel></primaryChannel>
</channel>
</channels>
- <eventDetails>
- <eventDetail>
<eventDetailsName></eventDetailsName>
<eventDetailsOrder></eventDetailsOrder>
<eventDetailsValue></eventDetailsValue>
</eventDetail>
- <eventDetail>
<eventDetailsName></eventDetailsName>
<eventDetailsOrder></eventDetailsOrder>
<eventDetailsValue></eventDetailsValue>
</eventDetail>
</eventDetails>
<eventDonationLinks />
<eventSanctions />
- <eventCategories>
- <eventCategory>
<categoryID></categoryID>
<categoryGroupCount></categoryGroupCount>
<categoryName></categoryName>
<categoryType></categoryType>
<categoryOrder></categoryOrder>
<numRegistered></numRegistered>
<maxRegistrations></maxRegistrations>
<percentFull></percentFull>
<displayDate></displayDate>
<closeDate></closeDate>
<actualCloseDate></actualCloseDate>
<isExpired></isExpired>
- <priceChanges>
- <priceChange>
<price></price>
<priceUntilDate></priceUntilDate>
</priceChange>
</priceChanges>
</eventCategory>
</eventCategories>
<eventUrl></eventUrl>
<eventContactUrl></eventContactUrl>
<eventImageUrl></eventImageUrl>
</event>
Any help would be appreciated!
The eventDetailsValue is in an array of eventDetail elements. So you need to diferentiate which element in the array you want. With this (and these LinqToXml extensions: http://searisen.com/xmllib/extensions.wiki) you can write it like this:
XElement doc = XElement.Parse(e.Result);
var details = doc.GetEnumerable("eventDetails/eventDetail", x => new
{
Name = x.Get("eventDetailsName", string.Empty),
Order = x.Get("eventDetailsOrder", string.Empty),
Value = x.Get("eventDetailsValue", string.Empty)
});
details is an IEnumerable<object> of Name's, Order's and the Value(s) you want. You can now loop through details and get the value(s) you want. I made Name, Order and Value all be strings, but by calling Get<type>("name", defaultValueByType) you can have them be other types instead.
You can loop through them like this:
foreach(var detail in details)
{
string value = detail.Value;
}
GetEnumerable is shorthand (in this case) for:
doc.Element("eventDetails").Elements("eventDetail").Select(x => new ...)
But it does null checking for you, which if your xml always produces the above xml, there would be no problems to do it long hand. And Get returns the proper value.
Note: Because this is a WindowsPhone7 project, you'll have to set a compiler flag of WindowsPhone7 so that the extensions compile without complaint (hopefully/I haven't tested it).
Try this query:
var xGood = from detaildoc in doc.Descendants("eventDetails")
select new
{
Value = detaildoc.Elements("eventDetail").Elements("eventDetailsValue").Value
};

XPath and attributes

I'm trying to traverse an XML document and select certain node attributes. The XML is dynamically generated.
<?xml version="1.0" encoding="ISO-8859-1"?>
<streams>
<stream>
<title>+23 (Panama)</title>
<info resolution="768x420" bitrate="1000kbps"/> ----- Need These
<swfUrl>http://www.freeetv.com/script/mediaplayer/player.swf</swfUrl>
<link>rtmp://200.75.216.156/live/</link>
<pageUrl>http://www.freeetv.com/</pageUrl>
<playpath>livestream</playpath>
<language>Music</language>
<advanced></advanced>
</stream>
</streams>
The code that I'm trying to use with zero luck and Visual Studio saying "No you're wrong. Try 600 more times" is
xDoc.Load("http://127.0.0.1/www/xml.php");
XmlNodeList nodes = xDoc.SelectNodes("/streams/stream");
foreach (XmlNode xn in nodes)
{
ListViewItem lvi = listView1.Items.Add(xn["title"].InnerText);
lvi.SubItems.Add(xn["swfUrl"].InnerText);
lvi.SubItems.Add(xn["link"].InnerText);
lvi.SubItems.Add(xn["pageUrl"].InnerText);
lvi.SubItems.Add(xn["playpath"].InnerText);
lvi.SubItems.Add(xn["language"].InnerText);
lvi.SubItems.Add(xn["advanced"].InnerText);
lvi.SubItems.Add(xn["//info/#resolution"].Value);
}
Please tell me oh wise ones what am I doing wrong?
If you want to select node's attribute using XPath you should use SelectSingleNode method, e.g.:
xn.SelectSingleNode("info/#resolution").Value
To select resolution attribute of your last node you need to use:
xn["info"].Attributes["resolution"].Value
Alternatively, you can try LINQ to XML for the same results (I find its API easier to use):
var doc = XDocument.Parse("http://127.0.0.1/www/xml.php");
foreach (var d in doc.Descendants("stream"))
{
ListViewItem lvi = listView1.Items.Add(d.Element("title").Value);
lvi.SubItems.Add(d.Element("swfUrl").Value);
// ...
vi.SubItems.Add(d.Element("info").Attribute("resolution").Value);
}
Here is an example of LINQ to XML to extract attributes from the entire document of a particular attribute name OR list of attribute names.
var xml = XElement.Parse("http://127.0.0.1/www/xml.php");
// find all attributes of a given name
var attributes = xml
.Descendants()
.Attributes("AttributeName")
// find all attributes of multiple names
var attributes = xml
.Descendants()
.Attributes()
.Where(a => ListOfAttribNames.Contains(a.Name.LocalName))
Replace:
lvi.SubItems.Add(xn["//info/#resolution"].Value);
with:
lvi.SubItems.Add(xn.SelectSingleNode("info/#resolution").Value);

Load repetitively-named XML nodes using Linq [C#]

I'm working on a program that needs to be able to load object-properties from an XML file. These properties are configurable by the user and XML makes sense to me to use.
Take the following XML document.
<?xml version="1.0" encoding="utf-8" ?>
<udpcommands>
<command name="requser">
<cvar name="reqchallege" value="false" />
</command>
<command name="reqprocs">
<cvar name="reqchallenge" value="false" />
</command>
</udpcommands>
I need to be able to load values from the cvars above to properties. I'm think Linq-To-XML would be good for it (I'm looking for applications of Linq so I can learn it). I've got a Linq-to-XML query done to select the right "command" based on the name.I was reading MSDN for help on this.
The following code snippet goes in a constructor that takes the parameter "string name" which identifies the correct XML <command> to pull.
I would like to have one linq statement to pull each <cvar> out of that XML given the section name, dumping everything to an IEnumerable. Or, I'm looking for a better option perhaps. I'm open for anything really. I would just like to use Linq so I can learn it better.
XElement doc = XElement.Load("udpcommands.xml");
IEnumerable<XElement> a = from el in doc.Elements()
where el.FirstAttribute.Value == name
select el;
foreach (var c in a)
{
Console.WriteLine(c);
}
The above code snippet outputs the following to the console:
<command name="requser">
<cvar name="reqchallege" value="false" />
</command>
Something like this should do:
var result =
doc.Elements("command")
.Single( x => x.Attribute("name").Value == name)
.Elements("cvar");
This will give you an IEnumerable<XElement> where each XElement represents a cvar in the specified command.
Note that if the specified command does not exist, the call to Single will cause an error. Likewise if the specified attribute is not found on the command.
EDIT As per your comments, you could do something along the lines of:
// Result will be an XElement,
// or null if the command with the specified attribute is not found
var result =
doc.Elements("command")
// Note the extra condition below
.SingleOrDefault( x => x.Attribute("name")!=null && x.Attribute("name").Value == name)
if(result!=null)
{
// results.Elements() gives IEnumerable<XElement>
foreach(var cvar in results.Elements("cvar"))
{
var cvarName = cvar.Attribute("name").Value;
var cvarValue = Convert.ToBoolean( cvar.Attribute("value").Value );
}
}

Categories