Why do I get false value for hasIdentifier variable, when I see in i-th document anything_start_i.xml that there is <identifier>value</identifier> element.
XDocument doc = XDocument.Load(args[0] + "/?verb=GetRecord&metadataPrefix=p3dm&identifier=" + i);
doc.Save("anything_start" + i + ".xml");
bool hasIdentifier = doc.Elements("identifier").Any();
Console.WriteLine(hasIdentifier);
Tried with Descendants instead of Elements, and again false.
XML:
<?xml version="1.0" encoding="utf-8"?>
<OAI-PMH xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">
<responseDate>...</responseDate>
<request verb="GetRecord" identifier="1"</request>
<GetRecord>
<record>
<header>
<identifier>1</identifier>
<datestamp>...</datestamp>
</header>
<metadata>
<P3DM xmlns="..." xsi:schemaLocation="...">
<MODELINFOID>1</MODELINFOID>
<TITLE>Roth</TITLE>
....
Well, I would like to save all documents, and trying to stop saving when there is no documents any more (actually there is but without meaningful data). So, this is how i started:
static void Main(string[] args)
{
var i = 1;
bool work = true;
do{
XDocument doc = XDocument.Load(args[0] + "/?verb=GetRecord&metadataPrefix=p3dm&identifier=" + i);
bool hasIdentifier = doc.Elements("identifier").Any();
if (hasIdentifier) {
doc.Save("anything" + i + ".xml");
i++;
}else{
work = false;
}
} while (work);
XNamespace ns = "you namespace goes here";
bool hasIdentifier = doc.Descendants(ns + "identifier").Any();
Related
I am trying to build a WebPage that includes "Rating of Site". Instead of using Database i am storing two variables to compute Avg of Rating in xml file as
<?xml version="1.0" encoding="utf-8"?>
<data>
<RatingCount>6</RatingCount>
<RatingTotal>17</RatingTotal>
</data>
Here is my Logic Code Both On the Page Load and AJAX Rating Control
Page_Load()
string rootPath = Server.MapPath("~/");
if (File.Exists(rootPath + "data.xml"))
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(rootPath + "data.xml");
XmlNode ratingCount = xdoc.DocumentElement.SelectSingleNode("/data/RatingCount");
XmlNode ratingTotal = xdoc.DocumentElement.SelectSingleNode("/data/RatingTotal");
string rating = ratingTotal.InnerText;
string count = ratingCount.InnerText;
if (Convert.ToInt32(count) >= 1)
{
double resultRating = Convert.ToSingle(rating) / Convert.ToSingle(count);
Rating1.CurrentRating = Convert.ToInt32(resultRating);
lblerror.Text = resultRating + " Rating in " + count + " Totals Votes";
}
else
{
lblerror.Text = "No Votes Till Now";
}
}
Rating_Control()
string rootPath = Server.MapPath("~/");
if (File.Exists(rootPath + "data.xml"))
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(rootPath + "data.xml");
XmlNode ratingCount = xdoc.DocumentElement.SelectSingleNode("/data/RatingCount");
XmlNode ratingTotal = xdoc.DocumentElement.SelectSingleNode("/data/RatingTotal");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter xwrite = XmlWriter.Create(rootPath + #"data.xml", settings);
xwrite.WriteStartDocument();
xwrite.WriteStartElement("data");
string r = (Convert.ToInt32(ratingCount.InnerText) + 1).ToString();
string t = (Convert.ToInt32(ratingTotal.InnerText) + Convert.ToInt32(e.Value)).ToString();
xwrite.WriteElementString("RatingCount", r);
xwrite.WriteElementString("RatingTotal", t);
xwrite.WriteEndElement();
xwrite.WriteEndDocument();
xwrite.Flush();
xwrite.Close();
}
else
{
lblerror.Text = "File Doesnt Exists";
}
Any Help will be Appreciated!
I have XML which is parsed into an XDocument:
<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>
<MyResponse xmlns="https://www.domain.net/">
<Node1>0</Node1>
</MyResponse>
</soap:Body>
</soap:Envelope>
Basically I am trying to create a new XDocument which has its root as
<MyResponse xmlns="https://www.domain.net/">
<Node1>0</Node1>
</MyResponse>
So in essence I am trying to extract this from the soap body. I have tried parsing this using Linq but cannot seem to return a new XDocument with this new root. Any ideas?
Thanks in advance
I think this will do the trick:
using System;
using System.Xml.Linq;
namespace SO39545160
{
class Program
{
static string xmlSource = "<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>" +
"<MyResponse xmlns = \"https://www.domain.net/\" >" +
"<Node1 > 0 </Node1 >" +
"</MyResponse>" +
"</soap:Body>" +
"</soap:Envelope>";
static void Main(string[] args)
{
XDocument xdoc = XDocument.Parse(xmlSource);
var subXml = xdoc.Document.Elements(XName.Get(#"{http://schemas.xmlsoap.org/soap/envelope/}Envelope")).Elements(XName.Get(#"{http://schemas.xmlsoap.org/soap/envelope/}Body")).Elements(XName.Get(#"{https://www.domain.net/}MyResponse"));
foreach (var node in subXml)
{
XDocument myRespDoc = new XDocument(node);
Console.WriteLine(myRespDoc);
}
Console.WriteLine();
Console.WriteLine("END");
Console.ReadLine();
}
}
}
I am trying to get the attribute values of all nodes with the tag name "Event" into a comboBox on a WindowsForm. I have tried this code below, however, nothing populates in the comboBox.
if (selectEventComboBox.SelectedIndex != -1)
{
string filePath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ "\\" + selectFileComboBox.SelectedItem.ToString()
+ "dogs.xml";
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList eventList = doc.GetElementsByTagName("Event");
for (int count = 0; count < eventList.Count; count++)
{
selectEventComboBox.Items.Add(eventList[count].Attributes.ToString());
}
}
This works fine
XmlDocument doc = new XmlDocument();
doc.Load("myxml.xml");
XmlNode root = doc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("//Event");
for (int i = 0; i < nodeList.Count; i++)
{
Console.WriteLine("row: {0}, InnerText: {1}, ID: {2}",i, nodeList[i].InnerText, nodeList[i].Attributes["id"].Value);
}
Contents of myxml.xml
<?xml version="1.0" encoding="utf-8" ?>
<root>
<Event id="1">Event one</Event>
<Event id="2">Event two</Event>
<Event id="3">Event three</Event>
<Event id="4">Event four</Event>
</root>
I am trying to add nodes to an xml document and then deleting them.
Adding nodes is working, but i cant remove nodes unless i restart the program.
The Write method:
public void writeToExistingDoc (String fileNamePath, int x, int y, int t)
{
string filename = fileNamePath;
string xPos = "" + x;
string yPos = "" + y;
string type = "" + t;
//create new instance of XmlDocument
XmlDocument doc = new XmlDocument ();
//load from file
doc.Load (filename);
//create node and add value
XmlNode node = doc.CreateNode (XmlNodeType.Element, "BUILDING", null);
XmlAttribute atr = doc.CreateAttribute ("x");
XmlAttribute atr2 = doc.CreateAttribute ("y");
XmlAttribute atr3 = doc.CreateAttribute ("type");
atr.Value = xPos;
atr2.Value = yPos;
atr3.Value = type;
node.Attributes.Append (atr);
node.Attributes.Append (atr2);
node.Attributes.Append (atr3);
//add to elements collection
doc.DocumentElement.AppendChild (node);
Debug.Log ("Element added");
//save back
doc.Save (filename);
}
and here is the Remove method:
public void removeBuildingNode (string fileNamePath, int buildingPosX, int buildingPosY)
{
XmlDocument doc = new XmlDocument ();
doc.Load (fileNamePath);
XmlNodeList nodes = doc.SelectNodes ("//BUILDING[#x='" + buildingPosX + "']");
for (int i = nodes.Count - 1; i >= 0; i--) {
Debug.Log("" + i);
nodes[i].ParentNode.RemoveChild (nodes[i]);
}
doc.Save(fileNamePath);
Debug.Log(""+buildingPosX + ", " + buildingPosY);
}
My XML doc looks like this:
<BUILDINGS ID="b">
<BUILDING x="50" y="80" type="1" />
<BUILDING x="25" y="125" type="1" />
<BUILDING x="35" y="125" type="1" />
<BUILDING x="45" y="125" type="1" />
</BUILDINGS>
As i've said, the methods work when i first run the program, use the write method, the restart the program and use the remove method. Wont work on the same running instance.
If you aren't bent on using XmlDocument, this should work...
Using: http://searisen.com/xmllib/extensions.wiki
public void removeBuildingNode (string fileNamePath, int buildingPosX, int buildingPosY)
{
XElement doc = XElement.Load(fileNamePath);
var nodesToRemove = doc.Elements("BUILDING")
.Where(xe => xe.Get("x", int.MinValue) == buildingPosX);
foreach(XElement node in nodesToRemove.ToArray())
node.Remove();
doc.Save(fileNamePath);
Debug.Log(""+buildingPosX + ", " + buildingPosY);
}
I need to get a value out of an XML file...
I have this XML file for example:
<?xml version="1.0"?>
<hwids>
<user>
<userName>Ivar</userName>
<hwid>BFEB-FBFF-0000-06FD-C87C-FA30</hwid>
</user>
<user>
<userName>Jerremy</userName>
<hwid>BFE9-FBFF-0000-06E8-E41E-5034</hwid>
</user>
</hwids>
Now, if I have the value BFEB-FBFF-0000-06FD-C87C-FA30, how do I get the name Ivar, out of the xml file trough C#?
I used in my application something like this:
using System.Data;
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFullPath, XmlReadMode.Auto);
DataRow[] dataRows = dataSet.Tables["user"].Select("hwid like 'BFEB-FBFF-0000-06FD-C87C-FA30'");
if (dataRows.Length == 0)
return;
string sUser = dataRows[0]["userName"].ToString();
you can accomplish this also with XmlDocument of the System.Xml namespace, which is supported in .NET 3.0
var xml = "<?xml version=\"1.0\"?>" +
"<hwids> " + "<user>" +
"<userName>Ivar</userName>" +
"<hwid>BFEB-FBFF-0000-06FD-C87C-FA30</hwid>"+
"</user> " +
"<user>" +
"<userName>Jerremy</userName>" +
"<hwid>BFE9-FBFF-0000-06E8-E41E-5034</hwid>" +
"</user>" +
"</hwids>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var ret = doc.GetElementsByTagName("userName");
for (int i = 0; i < ret.Count; i++)
{
Debug.WriteLine(ret.Item(i).InnerText);
}
I think this should work:
XElement root = XElement.Load("file.xml");
IEnumerable<XElement> hws =
from el in root.Elements("user")
where (string)el.Element("userName") == "Ivar"
select el.Descendant("hwid);
Haven't tested it out.