how to change a line(Config) in XML file - c#

I need to change the second line to config schema ="xxx.xsd" how can I do that ?
1<?xml version="1.0" encoding="utf-8"?>
2<**config**>
3<maketool-config>
.
.
.
</maketool-config>
</config>
here is the code :
XElement triggerRoot = new XElement("config",
new XElement("maketool-config",
);

var doc = new XmlDocument();
var triggerRoot = new XElement("config", new XElement("maketool-config", ""));
var newAttribute = doc.CreateAttribute("schema");
newAttribute.Value = "xxx.xsd";
triggerRoot.SetAttributeValue("schema", "xxx.xsd");

Related

XDocument just reads the first title?

I need to parse xml but my code just parses one title not all.
How can I parse part ?
This is my code:
CustomResponse itemCustom = new CustomResponse ();
XDocument response = XDocument.Parse(responseXml);
XElement rootElement = response.Root;
foreach (XElement sellResponse in rootElement.Elements())
{
itemCustom .ErrorCode = sellResponse.Element("ErrorCode").Value;
itemCustom .ErrorMessage = sellResponse.Element("ErrorMessage").Value;
itemCustom .CustomerID= sellResponse.Element("CustomerID").Value;
itemCustom .CustomerType= sellResponse.Element("CustomerType").Value;
}
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<TINS_XML_DATA>
<Header>
<ErrorCode>WAATS</ErrorCode>
<ErrorMessage>UTL</ErrorMessage>
</Header>
<Customer>
<CustomerID>UTL11111111111111111111</CustomerID>
<CustomerType>NSell</CustomerType>
</Customer>
</TINS_XML_DATA>
Try something like this:
foreach (XElement sellResponse in rootElement.Elements())
{
if (sellResponse.Name == "Header")
{
itemCustom.ErrorCode = sellResponse.Element("ErrorCode").Value;
itemCustom.ErrorMessage = sellResponse.Element("ErrorMessage").Value;
}
else if (sellResponse.Name == "Customer")
{
itemCustom.CustomerID = sellResponse.Element("CustomerID").Value;
itemCustom.CustomerType = sellResponse.Element("CustomerType").Value;
}
}
Update: You could also use XPath to find required elements as like below:
var xDoc = new XmlDocument();
xDoc.LoadXml(xml);
var errorMessage = xDoc.SelectNodes("//ErrorMessage")[0].InnerText;
This is my solved:
var xDoc = new XmlDocument();
xDoc.LoadXml(responseXml);
itemSell.ErrorCode = xDoc.SelectNodes("//ErrorCode")[0].InnerText;
itemSell.ErrorMessage = xDoc.SelectNodes("//ErrorMessage")[0].InnerText;
itemSell.CustomerID= xDoc.SelectNodes("//CustomerID")[0].InnerText;

Adding an XMLNode below a specific node

Here is my XML structure
<?xml version="1.0" encoding="utf-8"?>
<Projects xmlns="urn:projects-schema">
<Project>
<Name>Project1</Name>
<Images>
<Image Path="D:/abc.jpg"></Image>
</Images>
</Project>
</Projects>
I want to be able to Add a new Project Node though my code
And I want to be able to Create a new Image Node given a the Project Name
For the first task I have this so far:
try
{
var filename = Server.MapPath("~/App_Data/Projects.xml");
var doc = new XmlDocument();
if (System.IO.File.Exists(filename))
{
if (!ProjectExists(projectName))
{
doc.Load(filename);
var root = doc.DocumentElement;
var newElement = doc.CreateElement("Project");
root.AppendChild(newElement);
root = doc.DocumentElement;
newElement = doc.CreateElement("Name");
var textNode = doc.CreateTextNode(projectName);
root.LastChild.AppendChild(newElement);
root.LastChild.LastChild.AppendChild(textNode);
doc.Save(filename);
}
else
throw new ApplicationException("Project already exists");
doc = null;
}
}
catch (Exception ex)
{
throw ex;
}
But I am struggling for the second part. This is what I have so far:
if (System.IO.File.Exists(projectFilename))
{
doc.Load(projectFilename);
XmlNode root = doc.DocumentElement;
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("prj", "urn:projects-schema");
root = root.SelectSingleNode("descendant::prj:Project[prj:Name='" + projectName + "']", nsManager);
}
Any help will be appreciated. Thanks
XElement projects = XElement.Parse (
#"<Projects xmlns='urn:projects-schema'>
<Project>
<Name>Project1</Name>
<Images>
<Image Path='D:/abc.jpg'></Image>
</Images>
</Project>
</Projects>");
For Task 1, this can be done as follows:
projects.LastNode.AddAfterSelf(new XElement("Project",
new XElement("Name", "Project2"),
new XElement("Images",
new XElement("Image", "", new XAttribute("Path", "C:/abc.jpg"))
)));
Task 2:
projects.Descendants("Name")
.Where(x => x.Value == projectName).FirstOrDefault()
.AddAfterSelf(new XElement("Images",
new XElement("Image", "", new XAttribute("Path", "C:/def.jpg"))
)
);
EDIT: To check if an Images element exists and add a child Image element with an attribute to it
projects.Descendants("Project")
.Where(x => x.Elements("Images").Any())
.Descendants("Images").FirstOrDefault()
.Add(new XElement("Image", "", new XAttribute("Path", "D:/xyz.jpg")));

How to add elements in an XML file?

How should I add X there in XElement ?
XDocument triggerDocument = new XDocument(
new XDeclaration("1.0", "utf-8", null));
XElement triggerRoot = new XElement("config",
new XElement("maketool-config",
new XElement("hmi", new XElement("Messages",X))));
triggerDocument.Add(triggerRoot);
triggerDocument.Save(Path.Combine(outPath, "_triggers.xml"));
for (int i = 0; i <= events.Count; i++)
{
foreach (var item in events)
{
triggerRoot.Add(new XElement("n",
new XAttribute("page", item.page),
new XAttribute("sequence", item.sequence),
new XAttribute("priority", item.priority),
new XAttribute("errorText", item.errorText)
));
}
}
so it should look like this :
<?xml version="1.0" encoding="utf-8"?>
<config schema ="sdk-hmi.xsd">
<maketool-config>
<hmi>
<messages>
<n page="" sequence="" priority="" errorText="" />
<n page="" sequence="" priority="" errorText="" />
<n page="" sequence="" priority="" errorText="" />
<n page="" sequence="" priority="" errorText="" />
<n page="" sequence="" priority="" errorText="" />
</messages>
</hmi>
</maketool-config>
</config>
You can pass an XElement[] or IEnumerable<XElement> to XElement's constructor:
var messages = events.Select(item => new XElement("n",
new XAttribute("page", item.page),
new XAttribute("sequence", item.sequence),
new XAttribute("priority", item.priority),
new XAttribute("errorText", item.errorText)
));
XDocument triggerDocument = new XDocument(
new XDeclaration("1.0", "utf-8", null));
XElement triggerRoot = new XElement("config",
new XElement("maketool-config",
new XElement("hmi",
new XElement("Messages", messages))) // <<<--- This is the important part.
);
triggerDocument.Add(triggerRoot);
You can try this:
XDocument triggerDocument = new XDocument(
new XDeclaration("1.0", "utf-8", null));
XElement triggerRoot = new XElement("config",
new XElement("maketool-config",
new XElement("hmi", new XElement("Messages"))));
triggerDocument.Add(triggerRoot);
XElement msgNode = triggerRoot.Elements("Messages")
.SingleOrDefault();
if (msgNode != null)
{
foreach (var item in events)
{
msgNode.Add(new XElement("n",
new XAttribute("page", item.page),
new XAttribute("sequence", item.sequence),
new XAttribute("priority", item.priority),
new XAttribute("errorText", item.errorText)
));
}
}
May this will help to add nodes...
//file name
string filename = #"d:\temp\XMLFile2.xml";
//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, "Genre_Genre_Country", null);
node.InnerText = "this is new node";
//add to elements collection
doc.DocumentElement.AppendChild(node);
//save back
doc.Save(filename);

Writing Xml in Windows Phone Application

I have this code that work fine to create an xml document for my WPF application.
var doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
var parentNode = doc.CreateElement("manga");
doc.AppendChild(parentNode);
foreach (var mList in mangaList)
{
var itemNode = doc.CreateElement("item");
var itemAttribute = doc.CreateAttribute("value");
itemAttribute.Value = mList.Key;
itemNode.InnerText = mList.Value;
itemNode.Attributes.Append(itemAttribute);
parentNode.AppendChild(itemNode);
}
var writer = new XmlTextWriter(#"Data\mangalist.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
writer.Close();
Now I want to create similar application for Windows Phone 7.5 and i'm stuck in porting above code to be able to run in WP. After quick searching i found that XmlDocument is not available in Windows Phone and have to switch using XDocument. I am far from familiar with XDocument and hope somebody can help to me make my windows phone apps outputting the same xml.
Thanks
Solution :
After good hints from #Pradeep Kesharwani and #dav_i I managed to port those codes above to use XDocument and StreamWriter instead of XmlDocument and XmlTextWriter which are not available for WP:
var doc = new XDocument(new XDeclaration("1.0", "utf-8", "no"));
var root = new XElement("manga");
var mangaList = new Dictionary<string, string>();
mangaList.Add("conan", "conan");
mangaList.Add("naruto", "naruto");
foreach (var mList in mangaList)
{
var itemNode = new XElement("item");
var itemAttribute = new XAttribute("value", mList.Key);
itemNode.Value = mList.Value;
itemNode.Add(itemAttribute);
root.Add(itemNode);
}
doc.Add(root);
using (var writer = new StreamWriter(#"Data\mangalist2.xml"))
{
writer.Write(doc.ToString());
}
As I said in comments, XDocument is pretty straight forward -
new XDocument(
new XDeclaration("1.0", "utf-8", "no"),
new XElement("root",
new XElement("something",
new XAttribute("attribute", "asdf"),
new XElement("value", 1234),
new XElement("value2", 4567)
),
new XElement("something",
new XAttribute("attribute", "asdf"),
new XElement("value", 1234),
new XElement("value2", 4567)
)
)
)
Gives the following
<root>
<something attribute="asdf">
<value>1234</value>
<value2>4567</value2>
</something>
<something attribute="asdf">
<value>1234</value>
<value2>4567</value2>
</something>
</root>
Hopefully this will help you!
To automatically populate in a loop, you could do something like this:
var somethings = new List<XElement>();
for (int i = 0; i < 3; i++)
somethings.Add(new XElement("something", new XAttribute("attribute", i + 1)));
var document = new XDocument(
new XElement("root",
somethings));
Which results in
<root>
<something attribute="1" />
<something attribute="2" />
<something attribute="3" />
</root>
This Create method could be used to create a xml doc in wp7
private void CreateXml()
{
string xmlStr = "<RootNode></RootNode>";
XDocument document = XDocument.Parse(xmlStr);
XElement ex = new XElement(new XElement("FirstNOde"));
XElement ex1 = new XElement(new XElement("second"));
ex1.Value = "fdfgf";
ex.Add(ex1);
document.Root.Add(new XElement("ChildNode", "World!"));
document.Root.Add(new XElement("ChildNode", "World!"));
document.Root.Add(ex);
string newXmlStr = document.ToString();
}
This will be the created xml
<RootNode>
<ChildNode>World!</ChildNode>
<ChildNode>World!</ChildNode>
<FirstNOde>
<second>fdfgf</second>
</FirstNOde>
</RootNode>
public void ReadXml()
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("Your xml file name", FileMode.Open);
using (XmlReader reader = XmlReader.Create(isoFileStream))
{
XDocument xml = XDocument.Load(reader);
XElement root1 = xml.Root;
}
}

Creating XMLDocument throguh code in asp.net

am trying to generate an XML document like this through code.
<TestRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost:2292/RMSchema.xsd">
<Version>3</Version>
<ApplicationHeader>
<AppLanguage />
<UserId>rmservice</UserId>
</ApplicationHeader>
<CustomerData>
<ExistingCustomerData>
<MTN>2084127182</MTN>
</ExistingCustomerData>
</CustomerData>
</TestRequest>
I tried some samples. But they create xmlns for the children, which i dont need. Any help is really appreciated.
I have tried the below code. But it is adding only xmlns to all children, which i dont need
XmlDocument xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
XmlElement xRoot = xDocument.CreateElement("TestRequest", "XNamespace.Xmlns=http://www.w3.org/2001/XMLSchema-instance" + " xsi:noNamespaceSchemaLocation=" + "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = 1;
Thanks
Tutu
I have tried with
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
XmlElement xRoot = xDocument.CreateElement("xsi","RMRequest",xsi);
xRoot.SetAttribute("noNamespaceSchemaLocation", xsi, "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
Now the response is
<?xml version=\"1.0\" encoding=\"windows-1252\"?><xsi:TestRequest xsi:noNamespaceSchemaLocation=\"http://localhost:2292/RMSchema.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
Here is the awesome LINQ to XML. Enjoy!
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(new XDeclaration("1.0", "windows-1252", null),
new XElement("TestRequest",
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(xsi + "noNamespaceSchemaLocation", "http://localhost:2292/RMSchema.xsd"),
new XElement("Version",
new XText("3")
),
new XElement("ApplicationHeader",
new XElement("AppLanguage"),
new XElement("UserId",
new XText("rmservice")
)
),
new XElement("CustomerData",
new XElement("ExistingCustomerData",
new XElement("MTN",
new XText("2084127182")
)
)
)
)
);
doc.Save(filePath);
If you really want the old API, here it is:
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
var attr = xDocument.CreateAttribute("xsi", "noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
EDIT: From your comments, it looks like you want the xmlns:xsi and other attribute in that specific order. If so, you may have to trick the XmlDocument to add the xmlns:xsi attribute first.
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
// add namespace decl are attribute
var attr = xDocument.CreateAttribute("xmlns:xsi");
attr.Value = xsi;
xRoot.Attributes.Append(attr);
// no need to specify prefix, XmlDocument will figure it now
attr = xDocument.CreateAttribute("noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
Are you looking for something like this:-
XmlDocument xmldoc = new XmlDocument();
XmlNode root = xmldoc.AppendChild(xmldoc.CreateElement("Root"));
XmlNode child = root.AppendChild(xmldoc.CreateElement("Child"));
XmlAttribute childAtt =child.Attributes.Append(xmldoc.CreateAttribute("Attribute"));
childAtt.InnerText = "My innertext";
child.InnerText = "My node Innertext";
xmldoc.Save("ABC.xml");

Categories

Resources