@manhng

Welcome to my blog!

XML

June 3, 2021 17:41

XML (edit)

Vấn đề:

+ Tự tạo tệp XML bằng cách cộng chuỗi

+ Sau đó cần Serialize chuỗi thành Object

+ Lỗi: Cannot Convert XML to C# Object

XmlConvert.EncodeName(title);

Giải pháp:

You can use HttpUtility.HtmlEncode HttpUtility.HtmlDecode or with .NET 4.0+ you can also use WebUtility.HtmlEncode + WebUtility.HtmlDecode

Namespace:
System.Xml
Assembly:
System.Xml.ReaderWriter.dll
XmlConvert.EncodeName(title);

Refer

https://www.c-sharpcorner.com/UploadFile/mahesh/verify-xml-names-using-C-Sharp/

https://gist.github.com/jipengxiang/8611e4bf390bbf18ccc9

https://stackoverflow.com/questions/22906722/how-to-encode-special-characters-in-xml

https://stackoverflow.com/questions/8331119/escape-invalid-xml-characters-in-c-sharp

https://www.codeproject.com/Articles/1163664/Convert-XML-to-Csharp-Object

https://stackoverflow.com/questions/11447529/convert-an-object-to-an-xml-string

http://github.com/manhng83/NF452.ConsoleApp

enter image description here

Awesome WinUI

May 27, 2021 21:42

Awesome WinUI (edit)

WinUI (C#)

A collection of awesome resources for WinUI / Windows developers

scottkuhl/awesome-winui: A collection of awesome resources for WinUI / Windows developers. (github.com)

.NET Utilities (C#)

A general purpose utility and helper library for .NET development

RickStrahl/Westwind.Utilities: A general purpose utility and helper library for .NET development (github.com)

Working with XML Document (XML Utils) (XmlUtils)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace XmlGenCodeTool
{
[XmlRoot("MyDocument", Namespace = "http://www.dotnetcoretutorials.com/namespace")]
public class MyDocument
{
public string MyProperty { get; set; }

public MyAttributeProperty MyAttributeProperty { get; set; }

[XmlArray]
[XmlArrayItem(ElementName = "MyListItem")]
public List<string> MyList { get; set; }
}

public class MyAttributeProperty
{
[XmlAttribute("value")]
public int AValue { get; set; }
}

class Program
{
/// <summary>
/// https://dotnetcoretutorials.com/2020/04/23/how-to-parse-xml-in-net-core/
/// https://stackoverflow.com/questions/1880379/avoid-exception-on-xml-selectsinglenode-function
/// https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlnode.appendchild?view=net-5.0
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
#region Read XML

string path = "Test1.xml";

using (var fileStream = File.Open(path, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(MyDocument));
var myDocument = (MyDocument)serializer.Deserialize(fileStream);

Console.WriteLine(string.Format("My Property : {0}", myDocument.MyProperty));
Console.WriteLine(string.Format("My Attribute : {0}", myDocument.MyAttributeProperty.AValue));

foreach (var item in myDocument.MyList)
{
Console.WriteLine(item);
}
}

#endregion Read XML

#region Add new element

path = "Test2.xml";
XDocument doc = XDocument.Load(path);
XElement root = new XElement("Snippet");
root.Add(new XAttribute("name", "name goes here"));
root.Add(new XElement("SnippetCode", "SnippetCode"));
doc.Element("Snippets").Add(root);
doc.Save(path);

#endregion

#region Update Element

path = "Test3.xml";

string nodeId = "2";

XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.Load(path);
XmlNode node = xmlDoc2.SelectSingleNode("/Projects/Project[@ID=" + nodeId + "]");
node.Attributes["Name"].Value = "Project2_Update";

xmlDoc2.Save(path);

#endregion Update Element

#region Insert Element

// Input
/*
<Project>
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
<DefineConstants>TRACE;DEBUG;</DefineConstants>
</PropertyGroup>
</Project>
*/
// Output:
/*
<Project>
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
<DefineConstants>TRACE;DEBUG;</DefineConstants>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
</Project>
*/

path = @"C:\Git\Westwind.Utilities\Westwind.Utilities\Westwind.Utilities.csproj";
string attrName = "Condition";
string attrValue = "'$(Configuration)'=='Debug'";

string xmlString = File.ReadAllText(path, Encoding.UTF8);

XmlDocument xmlProject = new XmlDocument();
xmlProject.LoadXml(xmlString); // <PropertyGroup Condition="'$(Configuration)'=='Debug'">

//Find the specify node search by condition
var nodeList1 = xmlProject.SelectNodes("/Project/PropertyGroup");

for (int i = 0; i < nodeList1.Count; i++)
{
var node2 = nodeList1[i];

if (IsNodeAttributeEqualsSpecifyValue(node2, attrName, attrValue))
{
var nodeList2 = node2.SelectNodes("/Project/PropertyGroup/PlatformTarget");

var found = false;
for (int j = 0; j < nodeList2.Count; j++)
{
var node3 = nodeList2[j].ParentNode;
if (IsNodeAttributeEqualsSpecifyValue(node3, attrName, attrValue))
{
found = true;
break;
}
}

if (!found)
{
//Create a new node
XmlElement elem = xmlProject.CreateElement("PlatformTarget");
elem.InnerText = "x64";

//Add the node to the specify node
node2.AppendChild(elem);
}

break;
}
}

xmlProject.Save(path);

#endregion Insert Element

Console.WriteLine("Hello World");
}

private static bool IsNodeAttributeEqualsSpecifyValue(XmlNode parentNode, string attributeName, string attributeValue)
{
// <PropertyGroup Condition="'$(Configuration)'=='Debug'">
return parentNode.Attributes[attributeName] != null && parentNode.Attributes[attributeName].Value == attributeValue;
}
}
}

Convert JSON to XML

October 6, 2018 11:13

Convert JSON to XML (edit)

using Newtonsoft.Json;
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace Json2Xml
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ConvertJson2Xml();
            Console.Write("Successfully! Press any key to exit ");
            Console.ReadKey();
        }

        /// 
        /// Convert JSON to XML
        /// https://www.newtonsoft.com/json/help/html/ConvertJsonToXml.htm
        /// 1. Copy JSON from Web API
        /// 2. Format JSON from https://jsonformatter.org/ (replace ["] with [\"])
        /// 3. Convert JSON to XML
        /// 
        private static void ConvertJson2Xml()
        {
            string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string xmlRootFilePath = Path.Combine(desktopFolder, "root.xml");
            string jsonRootFilePath = Path.Combine(desktopFolder, "root.json");
            XmlDocument xmlDoc = new XmlDocument();
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
            var xmlDeclare = xmlDeclaration.OuterXml;
            string json = File.ReadAllText(jsonRootFilePath);
            XNode node = JsonConvert.DeserializeXNode(json, "root");
            string xmlContent = node.ToString();
            if (!xmlContent.Contains(xmlDeclare))
            {
                xmlContent = xmlContent.Insert(0, Environment.NewLine).Insert(0, xmlDeclare);
            }
            File.WriteAllText(xmlRootFilePath, xmlContent);
        }
    }
}

Sort XML

https://stackoverflow.com/questions/8749480/sort-xml-nodes-by-alpha-numeric-using-c-sharp

JSON Online Tools

Có chức năng view JSON dễ nhìn, trực quan

https://jsoneditoronline.org/

Có chức năng thu gọn JSON trên một dòng code

https://jsonformatter.org/

Web API AND XML

March 15, 2018 21:27

Code

Ví dụ

http://www.lateral8.com/articles/2010/3/5/openxml-sdk-20-export-a-datatable-to-excel.aspx

<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>AccountProblem</Code>
<Message>Your Google account is not currently enabled for this operation. Please check https://console.developers.google.com/billing to see if you have a past due balance or if the credit card (or other payment mechanism) on your account is expired. You can find additional information at https://developers.google.com/storage/docs/signup</Message>
<Details>The billing account for the requested project is disabled in state 'closed'</Details>
</Error>

Categories

Recent posts